如何正确使用Django反向FK查找以在CBV中显示子模型的实例 [英] How to correctly use Django reverse FK lookup to show instances of the child model in CBV

查看:64
本文介绍了如何正确使用Django反向FK查找以在CBV中显示子模型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,其中一个指向另一个,如下所示:

I have two models, field of one of them pointing to the other as shown below:

class Group(models.Model):
    group_company_id = models.CharField(primary_key=True, ...)
    
class Company(models.Model):
    company_id = models.CharField(primary_key=True, ...)
    group_company = models.ForeignKey(Group, related_name="related_grp_company", ...)

我正在尝试获取为特定创建的所有公司.因此,我试图在Djnago UpdateView 中获取 company_id (以及其他)值作为模板中的列表.我的CBV如下所示:

I am trying to get all the Companies that have been created for a particular Group. So I am trying to get the company_id (and other) values in Djnago UpdateView as a list in the template. My CBV is as shown:

class GroupCompanyChangeView(UpdateView):
    template_name =  ...
    model = Group
    form_class = ...
    success_url = reverse_lazy('group_list')

    grp_coy_units = Group.objects.prefetch_related('related_grp_company') # I am trying to get the values of `company_id` in the template but nothing is displayed.

有人可以让我知道如何使其正常工作吗?

如所解释的(@Mahmoud Adel),我已经修改了 UpdateView ,如下所示:

As explained (@Mahmoud Adel), I have modified my UpdateView as shown below:

class GroupCompanyChangeView(UpdateView):
    template_name =  ...
    model = Group
    form_class = ...
    success_url = reverse_lazy('group_list')

    def get_object(self, *args, **kwargs):
        return Group.objects.get(pk=self.kwargs['pk'])

然后在模板中,我正在做

And then in the template, I am doing:

{{group.related_grp_company}}

有了这个,我得到了< app> .Company.None 的输出.

With this I am getting an output of <app>.Company.None.

推荐答案

更新:在对我的本地环境进行测试以解决评论中报告的问题之后,这是最终答案

您应该覆盖 get_object()

def get_object(self, *args, **kwargs):
        try:
            return Group.objects.prefetch_related('related_grp_company').get(pk=self.kwargs['pk'])
        except:
            return None

请注意,上述查询中的顺序很重要,在 get 修复'Group'对象没有属性'prefetch_related'之前,先进行 prefetch_related 代码>.

Note that order matter here in the above query, doing prefetch_related before get fixes the error for 'Group' object has no attribute 'prefetch_related'.

此外,您可以使用 prefetch_related 删除,并且仅从上述查询中进行 get ,它也可以使用,但建议使用 prefetch_related 优化性能,因为您每次都会获取相关公司

Also, you can drop using prefetch_related and only do get from the above query and it will work too, but using prefetch_related is suggested to optimize performance as you will fetch the related companies every time

然后在您的 template 中,您可以简单地从对象调用 related_grp_company.all ,假设您正在将当前的 Group 对象传递为将 group 添加到您的模板中,因此它应该类似于 group.related_grp_company.all ,这是一个 QuerySet 列表,因此可以遍历它或执行任何操作想要.

Then at your template you can simply call related_grp_company.all from the object, let's say that you are passing the current Group object as group to your template, so it should like group.related_grp_company.all, this is a QuerySet list, so loop over it or do whatever you want.

例如:

{%for d in object.related_grp_company.all%}
<h1>{{ d.company_id }}</h1>
{% endfor %}

因为我们没有添加 all ,所以我们早先获得了< app> .Company.None

Because we didn't add all we were getting<app>.Company.None earlier

提示:

related_name 用于反向关系,我建议将其重命名为 companies ,这样对于例如:/p>

related_name is used for the reverse relation, I would suggest renaming it to companies so it would be more clearer, for ex:

group_company = models.ForeignKey(Group, related_name="companies", ...)

因此以后使用它就像 group.companies()

这篇关于如何正确使用Django反向FK查找以在CBV中显示子模型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆