Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django模型继承-查询中只需要父类的实例_Python_Django_Django Models_Django Queryset - Fatal编程技术网

Python Django模型继承-查询中只需要父类的实例

Python Django模型继承-查询中只需要父类的实例,python,django,django-models,django-queryset,Python,Django,Django Models,Django Queryset,假设我有两个模型,一个是另一个的父模型。我如何查询所有不是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_do

假设我有两个模型,一个是另一个的父模型。我如何查询所有不是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()

简单的方法是在
place
模型上有一个
place\u type
属性,然后覆盖
place
Restaurant
和任何其他基类的
save
,以便在持久化时正确设置它。然后可以使用
Place.objects.filter(Place\u type='Place')
进行查询。可能还有其他方法,但它们可能会很快变得毛茸茸的。

您可以检查是否存在小写模型名作为属性:

places = Place.objects.all()
not_restaurants = [p for p in places if not hasattr(p, 'restaurant')]

Django自动创建的
OneToOneField
上的过滤器。如果
为空
,则此
位置
不是
餐厅

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

谢谢,这是一个很好的解决方案。你应该使用数据库来过滤它,就像我听说过的那样,对子类进行过滤对性能有害吗?我不知道确切的原因,但我只是查看了这个查询,它看起来像是一个非常标准的联接。@Sabrinalegett涉及多个表的查询比只涉及一个表的查询慢,但是任何类型的关系数据库应用程序都会涉及联接。在这种情况下,任何涉及餐厅的事情都会涉及到两张桌子,因为这与地点是一对一的关系。这肯定比Python中的后期过滤要快得多,就像公认的答案:D