Django模型继承 - 只需要查询中父类的实例
假设我有两个模型,一个是另一个的父类。我如何查询Django中所有不是餐厅的地方? Place.objects.all()会包含所有的餐厅吗?我想排除结果中的孩子。谢谢!Django模型继承 - 只需要查询中父类的实例
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,您可以检查小写的型号名称存在作为一个属性:
places = Place.objects.all()
not_restaurants = [p for p in places if not hasattr(p, 'restaurant')]
最简单的办法是对Place
模型place_type
属性,然后覆盖save
为Place
,Restaurant
和任何其他的基类,当它坚持正确设置它。然后您可以使用Place.objects.filter(place_type='PLACE')
进行查询。可能还有其他方法,但他们很快就会变得非常毛茸茸。
谢谢,这是一个好主意。 – zallarak 2012-08-07 21:17:15
过滤器上Django的自动创建OneToOneField
。如果它IS NULL
,这Place
不是Restaurant
。
non_restaurant_places = Place.objects.filter(restaurant__isnull=True)
比公认的答案好得多 – 2017-01-28 12:05:29
谢谢,这是一个很好的解决方案。 – zallarak 2012-08-07 21:16:13