Django model inheritance - only want instances of

2019-05-26 06:36发布

问题:

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

回答1:

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')]


回答2:

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)


回答3:

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.