Reputation: 5371
I am working on the following:
# 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()
And I created the following data:
Business(1,'Company1')
Business(1,'Company2')
FinancialProduct(1,'Company1', 'Small Product')
FinancialProduct(1,'Company1,Company2', 'Large Product')
In the front end I get the following:
Select 'Small Product' > Get ('Company 1', 'Company 1', 'Company 2')
Select 'Large Product' > Get ('Company 1', 'Company 2')
Unfortunately I seem to be getting the data in the wrong way. What am I doing wrong with the third line of the __init__
? Is it because it's a M2M?
Upvotes: 0
Views: 697
Reputation: 5371
This absolutely fried my noodle (because all of this is highly counter intuitive) but I managed to come up with the following. I hope it helps someone:
self.fields['business'].queryset = Business.objects.filter(financialproduct__id=fpID.id)
Upvotes: 0
Reputation: 87095
This is wrong:
FinancialProduct(1,'Company1,Company2', 'Large Product')
You save an M2M with multiple queries. Say, like:
FinancialProduct(1,'Company1', 'Large Product').save()
FinancialProduct(1,'Company2', 'Large Product').save()
Upvotes: 1