简体   繁体   English

Django 外键:获取相关模型?

[英]Django Foreign Key: get related model?

Is it possible to get the related model of a foreign key through the foreign key field itself?是否可以通过外键字段本身获取外键的相关模型?

For example, if I have 3 models:例如,如果我有 3 个模型:

class ModelA(models.Model)
    field1 = models.CharField(max_length=10)

class ModelB(models.Model)
    field1 = models.CharField(max_length=10)

class ModelC(models.Model)
    field1 = models.CharField(max_length=10)
    field2 = models.ForeignKey(ModelA)
    field3 = models.ForeignKey(ModelB)

and I want to do:我想做:

for field in ModelC._meta.fields:
    if field.get_internal_type() == "ForeignKey":
        #get the related model for field e.g. ModelA or ModelB

Is this possible using just the models themselves rather than instances of the models?这是否可以仅使用模型本身而不是模型的实例?

If ModelA has an FK field named "foo", then this is how you can get the related model:如果 ModelA 有一个名为“foo”的 FK 字段,那么您可以通过以下方式获取相关模型:

ModelA._meta.get_field('foo').rel.to

With your code, it would look like:使用您的代码,它看起来像:

for field in ModelC._meta.fields:
    if field.get_internal_type() == "ForeignKey":
        print field.rel.to

If found it out by using tab completion in the shell long ago, it still works.如果很久以前在 shell 中使用选项卡完成发现它,它仍然有效。 You might want to learn to use the shell to reverse engineer stuff like that.您可能想学习使用 shell 对此类内容进行逆向工程。

Update for Django>=2.0 users更新 Django>=2.0 用户

Syntax has changed.语法已更改。 Use the below code to get the related model:使用以下代码获取相关模型:

ModelA._meta.get_field('foo').related_model

When trying to extract relations like this, I use a lot of command-line experimentation.在尝试提取这样的关系时,我使用了很多命令行实验。 A common pattern I use is _=starting_point.<chained_attributes>;pprint((_, dir(_))) .我使用的一个常见模式是_=starting_point.<chained_attributes>;pprint((_, dir(_))) For example:例如:

_=ModelC;pprint((_, dir(_)))
_=ModelC.field2;pprint((_, dir(_)))
_=ModelC.field2.field;pprint((_, dir(_)))
_=ModelC.field2.field.rel;pprint((_, dir(_)))
_=ModelC.field2.field.rel.to;pprint((_, dir(_)))

(You'll need to do from pprint import pprint first, naturally.) That lets me experiment with adding / removing attributes until a find the item I want... while seeing clearly what I've got and what's available at the next level down. (自然,您需要from pprint import pprint执行操作。)这让我可以尝试添加/删除属性,直到找到我想要的项目...同时清楚地看到我拥有的内容以及下一级可用的内容下。 From this, I get ModelC.field2.field.rel.to == ModelA .由此,我得到ModelC.field2.field.rel.to == ModelA The same base pattern can be used to explore reverse relationships, many-to-many relationships, starting with an instance rather than the class, etc.相同的基本模式可用于探索反向关系、多对多关系、从实例而不是类等开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM