Django查询在很多2字段上设置

时间:2011-06-27 09:19:38

标签: python django django-views

我正在研究以下内容:

# models.py

class FinancialProduct(models.Model):
    active = models.BooleanField(default=True)
    businesses = models.ManyToManyField(Business)
    name = models.CharField(max_length=40, unique=True)

class Item(models.Model):
    main_client = models.ForeignKey(Client)
    financial_product = models.ForeignKey(FinancialProduct)
    advisor = models.ForeignKey(User, blank=True, null=True)
    business = models.ForeignKey(Business)

class Business(models.Model):
    active = models.BooleanField(default=True)
    name = models.CharField(max_length=40, unique=True)

# forms.py

class ItemForm(ModelForm):

    def __init__(self,fpID,*args,**kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        self.fields['advisor'].queryset = User.objects.filter(groups__name='advisor')
        self.fields['business'].queryset = Business.objects.filter(financialproduct__businesses=fpID)

    class Meta:
        model = Item
        exclude = ('main_client', 'financial_product')

    def CustomSave(self,f,c,u):
        idb = self.save(commit=False)
        idb.financial_product = f
        idb.main_client = c
        return idb.save()

我创建了以下数据:

Business(1,'Company1')
Business(1,'Company2')
FinancialProduct(1,'Company1', 'Small Product')
FinancialProduct(1,'Company1,Company2', 'Large Product')

在前端,我得到以下内容:

Select 'Small Product' > Get ('Company 1', 'Company 1', 'Company 2')
Select 'Large Product' > Get ('Company 1', 'Company 2')

不幸的是,我似乎以错误的方式获取数据。我在__init__的第三行做错了什么?是因为它是M2M吗?

2 个答案:

答案 0 :(得分:1)

这是错误的:

FinancialProduct(1,'Company1,Company2', 'Large Product')

您使用多个查询保存M2M。比如说:

FinancialProduct(1,'Company1', 'Large Product').save()
FinancialProduct(1,'Company2', 'Large Product').save()

答案 1 :(得分:0)

这绝对炒我的面条(因为所有这些都非常反直觉)但我设法提出以下内容。我希望它可以帮到某人:

self.fields['business'].queryset = Business.objects.filter(financialproduct__id=fpID.id)