Let's say I have 2 models, one being the parent of another. How can I query all Places that aren't restaurants in Django? Place.objects.all() would include all restaurants right? I want to exclude the children from the results. Thank you!
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
The easy way is to have a
place_type
attribute on thePlace
model and then overridesave
forPlace
,Restaurant
and any other base class to set it properly when it's persisted. You could then query withPlace.objects.filter(place_type='PLACE')
. There could be other ways but they probably get very hairy very quickly.Filter on Django's automatically-created
OneToOneField
. If itIS NULL
, thisPlace
isn't aRestaurant
.According to the documentation, you can check for the existence of the lowercase model name as an attribute: