python - 查找将模型连接到“直通”模型的字段
问题描述
可以说我的模型定义为:
# The class that I will have the instance of.
class A(models.Model):
somefieldA = models.TextField()
m2mfield = models.ManyToManyField(B, through='AandB')
def __unicode__(self):
return self.somefieldA
# The model that participates in the m2m field.
class B(models.Model):
somefieldB = models.TextField()
def __unicode__(self):
return self.somefieldB
# Model that stores the extra information
# about the m2m rel.
class AandB(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
field1 = models.DecimalField()
field2 = models.TextField()
field3 = models.DateField()
我的要求是遍历模型中的所有对象AandB
。我知道我可以通过(这里有详细信息)来做到这一点:
# I have the instance of model A
for field in instance._meta.get_fields(include_hidden=True):
if field.one_to_many:
mgr = getattr(instance, field.get_accessor_name())
for obj in mgr.all():
# Do stuff here.
我的问题是,有什么方法可以通过AandB
模型链接到模型来获取字段名称A
?(在这种情况下是m2mfield
)。
解决方案
在这里的讨论之后,以及@schwobaseggl 在评论部分问我一个问题后突然出现的想法,我决定使用该related_name
属性来让我的生活更轻松。虽然我无法获得该字段的确切名称,但我可以通过我喜欢的任何名称related_name
最终得出我最初想要的结论。
# Model that stores the extra information
# about the m2m rel.
class AandB(models.Model):
a = models.ForeignKey(A, related_name='name_I_like_here')
b = models.ForeignKey(B)
field1 = models.DecimalField()
field2 = models.TextField()
field3 = models.DateField()
然后,我可以get_accessor_field()
用来获取相关的 AandB 模型,还可以像上面那样命名关系。这对我来说很有意义。我希望这也对其他人有所帮助。
同时,如果有人有任何其他建议,请随时发表评论或回答!
推荐阅读
- flutter - tflite 颤振应用程序仅提供一个输出
- android - jarsigner: the signer's certificate is self signed warning
- python - 如何在 gnumeric Python 插件函数代码中获取单元格的列号和行号?
- php - 如何在 laravel php 中从数据集编写子查询
- python - 如何将高音扬声器数据保存在 json 文件中?
- c# - 如何添加带参数值且不带 lambda 表达式的委托
- javascript - for 循环遍历 index[0] 两次
- python - 我需要创建一个 pandas 数据框,显示推文所代表的主题
- r - 将 data.frame 对象中的数值变量添加到包含 multpolygons 的 sf 对象
- spring - 使用 mongoDb(如 Firebase 或 Realtime Server 应用程序)的 Spring Boot