Question

I have a basic model called Restaurant

class Restaurant(models.Model):
    place = models.OneToOneField(Place, primary_key=True)
    serves_pizza = models.BooleanField()
    serves_hotdog = models.BooleanField()

    def __unicode__(self):
        return u'%s the restaurant' % self.place.name

Querying with Restaurant.objects.all() and Restaurant.objects.get() yields two different results in which only the former is correct.

# this is correct
>>> r=Restaurant.objects.all()
>>> r
[<Restaurant: Hogwarts the restaurant>, <Restaurant: Domino the restaurant>]
>>> r[0].serves_hotdog
True

# this is not correct
>>> r0=Restaurant.objects.get(pk=4556376185503744)
>>> r0.serves_hotdog
False

# although they have the same pk
>>> r0.pk == r[0].pk
True
# their property values are different
>>> r[0].serves_hotdog == r0.serves_hotdog
False
>>> r[0].serves_pizza == r0.serves_pizza
False

Has anyone seen anything similar to this?

Was it helpful?

Solution

If you are using Django-nonrel on GAE, make sure that you don't set primary_key=True for related models because the engine will use the same primary key for both models. For example, in my case, I have Restaurant and Place with OneToOneRelationship. If we use Place as primary key for Restaurant, a restaurant object created from a place object will share the same pk, thus messing up Restaurant.objects.get(pk=).

Dropping the primary key rule fixes my problem:

class Restaurant(models.Model):
    place = models.OneToOneField(Place) # no primary_key=True

I can't find this information elsewhere, so I'm posting it here. Hope it helps someone else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top