zallarak
zallarak

Reputation: 5515

Django model inheritance - only want instances of parent class in a query

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()

Upvotes: 7

Views: 3890

Answers (3)

Adam Bradley
Adam Bradley

Reputation: 1604

Filter on Django's automatically-created OneToOneField. If it IS NULL, this Place isn't a Restaurant.

non_restaurant_places = Place.objects.filter(restaurant__isnull=True)

Upvotes: 30

mVChr
mVChr

Reputation: 50185

According to the documentation, you can check for the existence of the lowercase model name as an attribute:

places = Place.objects.all()
not_restaurants = [p for p in places if not hasattr(p, 'restaurant')]

Upvotes: -1

tterrace
tterrace

Reputation: 1985

The easy way is to have a place_type attribute on the Place model and then override save for Place, Restaurant and any other base class to set it properly when it's persisted. You could then query with Place.objects.filter(place_type='PLACE'). There could be other ways but they probably get very hairy very quickly.

Upvotes: 2

Related Questions