Accessing table data created through manytomanyfield in django
I have this model file in which a user can own any number of farms and admin can create a charge and put it on one or many farms.The problem is that i want to access the table created through ManyToManyField in Charges model.I want to select only those rows of manytomanyfield that are related to a single user.
suppose if admin created a charge with id "3383" and selected five farms from MultiSelectWidget.In those five farms a user name "Mike" has two farms.ManyToManyField table will create 5 rows for in its table including 2 rows for user "Mike" farms .I want to access to those 2 rows but could not manage to get to those two rows.
Note: I just have the user id with me for look up
开发者_JS百科Models.py
class Farm(models.Model):
farmNo = models.CharField(max_length=100)
class FarmOwner(models.Model):
owner = models.ForeignKey(User)
farm = models.ManyToManyField(Farm)
class Charges(models.Model):
chargeId = models.CharField(max_length=100)
farms = models.ManyToManyField(Farm)
Please help
Thanks
Considering that the charge Id is 3383
and that the user is mike
you can get those 2 related rows by using this
mikes_farm_list = FarmOwner.Objects.filter(owner="Mike").values_list('farms', flat=True)
Charges.Objects.filter(chargeId=3383, farms__in=mikes_farm_list)
mike = Farm.objects.get(farmNo="Mike")
for charge in mike.charge_set.all():
print charge.chargeId
Check out the model field docs for a many to many. you can change the attribute name of "charge_set" to something else ("charges") by putting a related_name="charges" in your Charge model M2M declaration.
精彩评论