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

谢谢,这是一个很好的解决方案。 – zallarak 2012-08-07 21:16:13

最简单的办法是对Place模型place_type属性,然后覆盖savePlaceRestaurant和任何其他的基类,当它坚持正确设置它。然后您可以使用Place.objects.filter(place_type='PLACE')进行查询。可能还有其他方法,但他们很快就会变得非常毛茸茸。

+0

谢谢,这是一个好主意。 – zallarak 2012-08-07 21:17:15

过滤器上Django的自动创建OneToOneField。如果它IS NULL,这Place不是Restaurant

non_restaurant_places = Place.objects.filter(restaurant__isnull=True) 
+1

比公认的答案好得多 – 2017-01-28 12:05:29