您可能可以通過自省來解決這個問題,但是您會將模型與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。 –