![](/img/trans.png)
[英]Whether to (and how to) handle multiple many-to-many relationship through a common intermediary/join table in django?
[英]how can i access to the intermediary table fields through the parent table in django?
这是我的桌子:
class MyUser(models.Model):
pass
class Product(models.Model):
name = models.CharField()
class Order(models.Model):
customer = models.ForeignKey(MyUser, on_delete=models.CASCADE)
products = models.ManyToManyField(Product , through='MidCartProduct')
class MidCartProduct(models.Model):
class Meta :
unique_together = (('order_id' , 'product_id'))
order_id = models.ForeignKey(Order , on_delete=models.CASCADE)
product_id = models.ForeignKey(Product , on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField()
那么如何通过Order
表访问中间表quantity
字段呢? 那可能吗?
我试图这样做但不工作:
>>> a = Order.objects.first().products.first()
>>> a.quantity
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Order' object has no attribute 'quantity'
对不起,我的英语不好
您改为遍历midcartproduct_set
:
myorder = Order.objects.first()
for midcartproduct in myorder.midcartproduct_set.all():
print(midcartproduct.quantity, midcartproduct.product_id)
由于您可能需要所有Product
,因此您最好为此添加一个.select_related(…)
[Django-doc] :
myorder = Order.objects.first()
for midcartproduct in myorder.midcartproduct_set.select_related('product_id'):
print(midcartproduct.quantity, midcartproduct.product_id)
注意:通常不会将后缀
_id
添加到ForeignKey
字段,因为 Django 会自动添加带有_id
后缀的“twin”字段。 因此它应该是product
,而不是。product_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.