Django表单 - 在模型中过滤外键

时间:2014-02-14 18:14:15

标签: python django django-models django-forms

我们假设我们有两个模型:

class Entry(models.Model):
    number = models.IntegerField(blank=True, null=True, verbose_name="#")
    product = models.ForeignKey(Application, blank=True, null=True, verbose_name='Application')

class Application(models.Model):
    name = models.CharField(max_number=100)
    defaultCalendar = models.ForeignKey(Calendar)
class Calendar(models.Model):
    name = models.CharField(max_number=100)

并形成:

class EntryForm(ModelForm):

class Meta:
    model = Entry
    fields = {'product ', 'number'}

1)在文档中我们可以读到使用fields我们可以更改模型的顺序,但是在这个例子中它不起作用:(

2)有没有办法在我的表格中过滤产品?在模型的视图中我可以这样做

def somefunction(request, val1, val2):
    products = Application.objects.filter(defaultCalendar=request.user.get_profile().defaultCalendar)

get_profile是一个返回用户个人资料的函数。

无论如何要在Form中做到这一点? filter参数必须与执行该函数的usere连接。

提前致谢

1 个答案:

答案 0 :(得分:3)

1)它不起作用,因为“fields”应该是一个列表:

fields = ['product ', 'number', ]

2)

您可以使用:

form.fields["product"].queryset = your_queryset