Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 397
zallarak Avatar asked Aug 07 '12 20:08

zallarak


People also ask

What class does a Django model class inherit?

The basics: Each model is a Python class that subclasses django.db.models.Model . Each attribute of the model represents a database field.

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.

What is proxy model inheritance in Django?

The main Usage of a proxy model is to override the main functionality of existing Model. It is a type of model inheritance without creating a new table in Database. It always query on original model with overridden methods or managers.

What is abstract inheritance in Django?

An abstract model is a base class in which you define fields you want to include in all child models. Django doesn't create any database table for abstract models. A database table is created for each child model, including the fields inherited from the abstract class and the ones defined in the child model.


1 Answers

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)
like image 92
Adam Bradley Avatar answered Sep 25 '22 23:09

Adam Bradley