Django model inheritance - only want instances of

2019-05-26 06:31发布

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

3条回答
成全新的幸福
2楼-- · 2019-05-26 07:06

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-05-26 07:07

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)
查看更多
Lonely孤独者°
4楼-- · 2019-05-26 07:18

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')]
查看更多
登录 后发表回答