具有特定字段的自定义查询集的 Django ModelForm 实例 [英] Django ModelForm instance with custom queryset for a specific field

查看:21
本文介绍了具有特定字段的自定义查询集的 Django ModelForm 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与以下类似的模型:

I have a model not unlike the following:

class Bike(models.Model):
    made_at = models.ForeignKey(Factory)
    added_on = models.DateField(auto_add_now=True)

所有用户可能在多个工厂工作,因此他们的用户配置文件都有一个ManyToManyFieldFactory.

All users may work at a number of factories and therefore their user profiles all have a ManyToManyField to Factory.

现在我想为 Bike 构建一个 ModelForm 但我希望 made_at 列表只包含当前用户工作的工厂.这个想法是,用户应该能够添加他们组装的自行车,并输入自行车的制造工厂.

Now I want to construct a ModelForm for Bike but I want the made_at list to consist of only factories at which the current user works. The idea is that users should be able to add bikes that they've assembled and enter which of the factories the bike was made at.

我该怎么做?

推荐答案

您的问题可能是重复这个.

S.洛特答案 有一张票可以解决您的问题.他回答:

S. Lott's answer there is the ticket to solve your problem. He answered:

ForeignKey 由 django.forms.ModelChoiceField 表示,它是一个 ChoiceField,其选择是一个模型 QuerySet.请参阅 ModelChoiceField 的参考.

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

因此,为字段的 queryset 属性提供一个 QuerySet.取决于您的表单的构建方式.如果您构建一个显式表单,您将拥有直接命名的字段.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id)如果采用默认的 ModelForm 对象,form.fields["rate"].queryset = ...

form.rate.queryset = Rate.objects.filter(company_id=the_company.id) If you take the default ModelForm object, form.fields["rate"].queryset = ...

这是在视图中明确完成的.没有黑客攻击.

This is done explicitly in the view. No hacking around.

这篇关于具有特定字段的自定义查询集的 Django ModelForm 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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