6

假设我有 2 个模型,一个是另一个模型的父级。如何在 Django 中查询所有不是餐厅的地方?Place.objects.all() 将包括所有餐馆,对吗?我想从结果中排除孩子。谢谢!

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()
4

3 回答 3

24

过滤 Django 的自动创建的OneToOneField. 如果是IS NULL,这Place不是一个Restaurant

non_restaurant_places = Place.objects.filter(restaurant__isnull=True)
于 2015-08-18T20:46:26.500 回答
1

简单的方法是在模型上有一个place_type属性Place,然后覆盖saveforPlaceRestaurant任何其他基类,以便在持久化时正确设置它。然后您可以使用 查询Place.objects.filter(place_type='PLACE')。可能还有其他方法,但它们可能很快就会变得非常多毛。

于 2012-08-07T20:56:08.470 回答
-1

根据文档,您可以检查小写模型名称是否存在作为属性:

places = Place.objects.all()
not_restaurants = [p for p in places if not hasattr(p, 'restaurant')]
于 2012-08-07T21:00:29.953 回答