访问django中通过manytomanyfield创建的表数据
我有这个模型文件,其中用户可以拥有任意数量的农场,管理员可以创建费用并将其放在一个或多个农场上。问题是我想访问通过 ChargesManyToManyField 创建的表强>模型。我只想选择与单个用户相关的manytomanyfield的那些行。
假设管理员创建了 ID 为 “3383” 的费用,并从 MultiSelectWidget 中选择了五个农场。在这五个农场中,用户名“Mike”有两个农场。ManyToManyField 表将创建其表中有 5 行,其中包括用户“Mike”农场的 2 行。我想访问这两行,但无法设法访问这两行。
注意:我只有用户 ID 来查找
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)
请帮忙,
谢谢
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑到费用 ID 为
3383
并且用户为mike
,您可以使用以下方法获取这 2 个相关行Considering that the charge Id is
3383
and that the user ismike
you can get those 2 related rows by using this查看多对多的模型字段文档。您可以通过在 Charge 模型 M2M 声明中放置 related_name="charges" 来将“charge_set”的属性名称更改为其他名称(“charges”)。
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.