django:在多表继承中将关系向后追溯到子类 [英] django: following relationship backwards to subclass in multi-table inheritance

查看:54
本文介绍了django:在多表继承中将关系向后追溯到子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很乐意为您提供帮助.在多表继承情况下,我试图将关系追溯到子类.

I would welcome any help with my problem. I'm trying to follow a relationship backwards to a subclass in a multi-table inheritance situation.

即我想要一个特定状态下所有餐厅的查询集.

I.e. I would like a queryset of all restaurants in a particular state.

这是我的问题的简化示例(对django文档中的eg的修改);

Here is a simplified example of my question (a modification on the eg in django's documentation);

from django.db import models

class Place(models.Model):
    state = models.ForeignKey('State')
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

class Restaurant(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

class State(models.Model):
    state = models.CharField(max_length=50)

如果我尝试 state.restaurant_set.all()我会收到异常

If I try state.restaurant_set.all() I receive an exception

状态"对象没有属性"Restaurant_set"

'State' object has no attribute 'Restaurant_set'

但是,如果我尝试使用state.place_set.all(),则会收到该州的一组地点查询,但是我真的只是想要该州的餐馆.

however if I try state.place_set.all() I receive a query set of places in that state, but I really just want restaurants in the state.

任何人都可以提供一些有关如何正确地表达我的查询集的建议,或者提供其他一些有关如何实现这一点的想法吗?

Can anyone provide some suggestions on how to correctly formulate my queryset, or provide some other ideas on how to achieve this?

任何帮助将不胜感激

推荐答案

您不能将外键从 State 倒退到 Restaurant ,但是可以实现通过使用餐厅的继承外键进行过滤以得出相同的结果:

You can't follow the foreign key backwards from State to Restaurant, but you can achieve the same result by filtering using the restaurant's inherited foreign key to state:

restaurants = Restaurant.objects.filter(state=state)

这篇关于django:在多表继承中将关系向后追溯到子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆