سؤال

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?

هل كانت مفيدة؟

المحلول

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)

نصائح أخرى

Just to add a reason to the answer of Alvaro (since you say in your comment you don't understand why):

Take this as an example: A --> B (A = source, B = target)

If you are haveing a one-to-one relation, it implies that if you have one source A, you have a relation to one specific target B (otherwise ot would be one-to-many). For target B, the only related source element can be A, since it is allowed to relate just to one (one-to-one), otherwise it would be many-to-one.

A ForeignKey allows to refer many objets to one related object

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top