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

查看:226
本文介绍了具有特定字段的自定义查询器的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)

用户可以在多个工厂工作,因此他们的用户配置文件都有一个 ManyToManyField Factory

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.

我该怎么做? / p>

How do I do that?

推荐答案

你的问题可能是一个 dupe这个

S上。 Lott 答案有机会解决你的问题。
他回答:

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


ForeignKey由django.forms.ModelChoiceField表示,它是一个ChoiceField,它的选择是一个ModelSet模型。请参阅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 = ...

这是在视图中显式完成的。没有黑客。

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

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

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