您可能可以通过自省来解决这个问题,但是您会将模型与Django实现紧密耦合,这可能很危险。如果你善于与,你可以做线沿线的东西:
class MyModel(models.Model):
## Definitions
@property
def related(self):
related = []
for attr in dir(self):
try:
## Get the class name.
attr_type = type(bf.__getattribute__(attr)).__name__
## This is an internal type tucked away in:
## django/db/models/fields/related.py
## As best I can tell, this is only used for reverse
## relationships.
if attr_type == "RelatedManager":
related.extend(bf.__getattribute__(attr).all())
except:
## Some of the built in methods/properties throw errors,
## skip them.
pass
return related
可能不是最好的解决办法,但它似乎在测试工作。
我有一个照片模型类似的问题,并需要知道每一个这样的特定照片使用(权利管理问题)。我发现的唯一方法是通过每个对象链发出单独的查询。我很想知道是否还有更好的方法,因为它确实感觉不对,并且非常违反DRY。 –