Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Django OneToOneField needs to be unique?

I get a "column template_id is not unique" error, now let me explain. I have a template model and a player version of it.

Template:

class FarmTemplate(models.Model):
    """Template of the "Farm" building"""

    name = models.CharField(max_length=23)
    flavor = models.TextField()
    resource = models.CharField(max_length=23)
    version = models.FloatField(unique=True)

    def __unicode__(self):
        return self.name

My User model:

class Farm(models.Model):
    """Keeps track of Townhall"""

    user = models.ForeignKey(User)
    template = models.OneToOneField(FarmTemplate)
    level = models.IntegerField()

    def __unicode__(self):
        return "User: %s, Farm level: %s" % (self.user, self.level)

When I create my first object everything goes right, however, when I create a second it tells me the OneToOneField isnt unique (which is correct since it uses the same template. But I have no clue why this needs to be unique.. Can someone please explain where I went wrong?

like image 724
Hans de Jong Avatar asked Jan 03 '14 17:01

Hans de Jong


People also ask

What is OneToOneField in Django models?

One-to-one fields: This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way.

How do I get OneToOneField in Django?

Accessing OneToOneField Model fields in Django TemplatesGet all the objects of the model 'Contact' in your views.py file. And pass this to the template. Now, go to your HTML template and add this code.


1 Answers

OnetoOne means each tuple is unique. I think you should use ForeignKey:

class Farm(models.Model):
"""Keeps track of Townhall"""

user = models.ForeignKey(User)
template = models.ForeignKey(FarmTemplate)
level = models.IntegerField()

def __unicode__(self):
    return "User: %s, Farm level: %s" % (self.user, self.level)
like image 190
Alvaro Avatar answered Sep 20 '22 00:09

Alvaro