Django形式来自相关模型

时间:2009-12-30 19:40:12

标签: django django-models django-forms

你有模特:

class Order(Model):
 date = DateField(editable = False, auto_now_add=True)
 status = CharField(max_length = 1, choices = STATUS, default = 'N')
 profile = ForeignKey(Profile, related_name = 'orders', blank = True, null = True)
 shipping = ForeignKey(Shipping, related_name = 'orders', blank = True, null = True)
 address = ForeignKey(Address, related_name = 'address_orders', blank = True, null = True)
 company = ForeignKey(Company, related_name = 'company_orders', blank = True, null = True)

class Address(Model):
 address_profile = ForeignKey(Profile, related_name = 'addresses')
 city = CharField(max_length = 256, blank = True, null = True)
 street = CharField(max_length = 256, blank = True, null = True)
 zipcode = CharField(max_length = 10, blank = True, null = True)
 phone = CharField(max_length = 23, blank = True, null = True)

class Company(Address):
 company_profile = ForeignKey(Profile, related_name = 'companies')
 name = CharField(max_length = 256, blank = True, null = True)
 company_id = CharField(max_length = 256, blank = True, null = True)

如何为指定的个人资料创建OrderForm?有了这个

class OrderCheckoutForm(forms.ModelForm):
 class Meta:
  model = Order

我收到一份包含所有地址和公司的表格。我想限制它们与它的配置文件相关。有没有简单解决方案?

提前致谢, 艾格。

1 个答案:

答案 0 :(得分:3)

您可以将查询集提供给ModelChoiceField(这是ModelForms用于ForeignKeys的内容;您可以在django/forms/models.py中找到它)。像,

class OrderCheckoutForm(forms.ModelForm):
    profile = models.ModelChoiceField(queryset = Profile.objects.filter(...))

    class Meta:
        model = Order

当然,您的过滤标准取决于您要完成的工作,而不是原始帖子中的100%明确。