访问django中通过manytomanyfield创建的表数据

发布于 2024-12-01 16:15:53 字数 766 浏览 0 评论 0原文

我有这个模型文件,其中用户可以拥有任意数量的农场,管理员可以创建费用并将其放在一个或多个农场上。问题是我想访问通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝颜夕 2024-12-08 16:15:53

考虑到费用 ID 为 3383 并且用户为 mike,您可以使用以下方法获取这 2 个相关行

mikes_farm_list = FarmOwner.Objects.filter(owner="Mike").values_list('farms', flat=True)
Charges.Objects.filter(chargeId=3383, farms__in=mikes_farm_list)

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)
避讳 2024-12-08 16:15:53
mike = Farm.objects.get(farmNo="Mike")
for charge in mike.charge_set.all():
    print charge.chargeId

查看多对多的模型字段文档。您可以通过在 Charge 模型 M2M 声明中放置 related_name="charges" 来将“charge_set”的属性名称更改为其他名称(“charges”)。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文