views:

360

answers:

1

I have one Product Model that has a FK to price, as one product can contain many prices. But I also want to be able to pick which one of those many prices should be the actual price, therefore I have both price (in Product Model) and product (in Price Model) to accomplish this. Consider these following models:

class Product(models.Model):
name = models.CharField()
price     = models.ForeignKey('Price', blank=True, null=True, related_name='Product')

class Price(models.Model):
amount = models.IntegerField()
product = models.ForeignKey('Product', related_name='product')

This works fine although I am having problem filtering the prices in the drop down menu. It gives me all the prices instead of just the prices that pertains to that product. Tried

limit_choices_to

but that doesn't seem to work with dynamic values.

I have also come across this patch: http://code.djangoproject.com/ticket/2445

Not sure what the best solution would be here. Would appreciate some pointers, thanks!

A: 

You could do:

prices = price.object_set_all(product='your product')

I left the tag 'your product' in because I don't recall if self will work in this situation. However I think this may be the correct approach.

You should not have the ForeignKey showing up in both models, you really only need it in Price. Then, your Product model can have a field called current_price which is based on a user selection.

AlbertoPL
Thanks for your reply AlbertoPL I get: 'ForeignKey' object has no attribute 'object_set' or: 'ForeignKey' object has no attribute 'object_set_all' on: price = models.ForeignKey('Price') prices = data.object_set_all(product='your product') Also I am not sure how the current_price field in the Product model should look.
orwellian
That's because I told you the completely wrong this heh, it should beProduct.objects.all() <- and you can filter by whatever field you wish within the parenthesis.
AlbertoPL
Rather, it should be Price.objects.all(), sorry.
AlbertoPL
Then I get NameError: name 'Product' is not defined. Lowercase gives another error. Are you sure I can do this in a module definition?
orwellian
No, and in fact, I think it should be done in views instead. Otherwise, I would just use a ManyToManyField, which is defined only in a single model (either Product or Price). Let me know what you end up doing.
AlbertoPL