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

我与影子孤独终老i 提交于 2019-12-22 20:42:23

问题


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.



来源:https://stackoverflow.com/questions/11853850/django-model-inheritance-only-want-instances-of-parent-class-in-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!