以编程方式识别 django 外键链接但通过表省略

发布于 2025-01-06 13:01:50 字数 657 浏览 1 评论 0原文

我之前提出了一个问题,以编程方式识别外键链接。

我发现下面的代码提取了所有一对多链接:

yourModel._meta.get_all_related_objects()

不过,我现在发现的唯一问题是它还包含通往多对多链接的中间表。因此,如果我有以下模型,

class Model_one(models.Model):
    name = models.CharField("Name", max_length=30)
    people = models.ManyToManyField('Model_two', blank=True, through='Association')

代码不会返回任何内容,而是返回 Association。有没有办法指定“真正的”一对多链接或以其他方式通过表格省略?即使我必须从返回的 yourModel._meta.get_all_lated_objects() 中手动删除它?

另一种提问方式是:如何识别/隔离实际上是“直通”表的链接?

I asked a question earlier to programmatically identity foreignkey links..

I found that the below code pulls all the one-to-many links:

yourModel._meta.get_all_related_objects()

The only problem I'm finding now though is that it also includes interemdiary tables that are going to many-to-many links. So if I have the below model,

class Model_one(models.Model):
    name = models.CharField("Name", max_length=30)
    people = models.ManyToManyField('Model_two', blank=True, through='Association')

Instead of returning nothing, the code returns Association. Is there a way to either specify "real" one-to-many links or otherwise omit through tables? Even if I have to delete it manually from the returned yourModel._meta.get_all_related_objects()?

Another way to ask this: How can I identify/isolate a link that is actually a "through" table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

当梦初醒 2025-01-13 13:01:50

您可以测试每个项目,看看它是否在 _meta.get_all_lated_many_to_many_objects() 中:

related_m2ms = MyModel._meta.get_all_related_many_to_many_objects()
for related in MyModel._meta.get_all_related_objects():
     if related not in related_m2ms:
         # Do something here with only one-to-many relationships

You can test each item to see if it's in _meta.get_all_related_many_to_many_objects():

related_m2ms = MyModel._meta.get_all_related_many_to_many_objects()
for related in MyModel._meta.get_all_related_objects():
     if related not in related_m2ms:
         # Do something here with only one-to-many relationships
天赋异禀 2025-01-13 13:01:50

发现一个问题引导我正确的方向:

m2m_links =MyModel._meta.local_many_to_many
for r in m2m_links:
    if not r.rel.through._meta.auto_created:
        print r.rel.through._meta.object_name

这将给出“通过”表的名称

Found a question that led me in the right direction:

m2m_links =MyModel._meta.local_many_to_many
for r in m2m_links:
    if not r.rel.through._meta.auto_created:
        print r.rel.through._meta.object_name

This will give the name of the "through" tables

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文