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

假装没事ソ 提交于 2019-12-06 05:51:19

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

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)

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.

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