Django查询相关对象

发布于 2024-12-12 07:12:22 字数 302 浏览 0 评论 0原文

我有这样的模型:

class A(Model):
    ....

class B(Model):
    a = ForeignKey(A, related_name="bbb")

class C(Model)
    b = ForeignKey(B, related_name="ccc")
    file = FileField( ... , null=True, blank=True)

在模板或视图中,如果与 A 相关的某个 C 对象具有 file=None (null) ,我需要标记 A 行。 谢谢。

I have models like this:

class A(Model):
    ....

class B(Model):
    a = ForeignKey(A, related_name="bbb")

class C(Model)
    b = ForeignKey(B, related_name="ccc")
    file = FileField( ... , null=True, blank=True)

In template or in view I need a mark A row, if some C object related to A has file=None (null) .
Thanks.

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

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

发布评论

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

评论(1

谁的年少不轻狂 2024-12-19 07:12:22

如果我理解正确,请尝试以下操作:

for a in A.objects.all():
    for b in a.bbb.all():
        for c in b.ccc.filter(file__isnull=True):
            a.has_c_with_null_file = True
            a.save()

OR

    c_without_file = C.objects.filter(file__isnull=True)
    for c in c_without_file:
        c.b.a.has_c_with_null_file = True
        c.b.a.save()

OR

    A.objects.filter(b__c__file__isnull=True).update(has_c_with_null_file=True)

如果您省略相关名称,请使用 b_set 和 c_set。

If I understand correctly, try this:

for a in A.objects.all():
    for b in a.bbb.all():
        for c in b.ccc.filter(file__isnull=True):
            a.has_c_with_null_file = True
            a.save()

OR

    c_without_file = C.objects.filter(file__isnull=True)
    for c in c_without_file:
        c.b.a.has_c_with_null_file = True
        c.b.a.save()

OR

    A.objects.filter(b__c__file__isnull=True).update(has_c_with_null_file=True)

If you leave off the related name, use b_set and c_set.

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