Django模型继承-仅在查询中需要父类的实例 [英] Django model inheritance - only want instances of parent class in a query
本文介绍了Django模型继承-仅在查询中需要父类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有2个模型,一个模型是另一个模型的父模型。如何在Django中查询不是餐厅的所有地方? Place.objects.all()将包括所有餐厅,对吗?我想从结果中排除孩子们。谢谢!
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()
推荐答案
根据文档,您可以检查是否存在小写模型名称作为属性:
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')]
这篇关于Django模型继承-仅在查询中需要父类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文