Django获得相关对象ManyToMany关系

时间:2016-10-19 20:15:31

标签: python django

我有两种模式:

class CartToys(models.Model):
    name = models.CharField(max_length=350)
    quantity = models.IntegerField()

class Cart(models.Model):
    cart_item = models.ManyToManyField(CartToys)

我想把所有相关玩具都放到这个购物车上。我怎么能这样做

1 个答案:

答案 0 :(得分:1)

你会用...

cart = Cart.objects.first()
objects = cart.cart_item.all() # this line return all related objects for CartToys
# and in reverse
cart_toy = CartToys.objects.first()
carts = cart_toy.cart_set.all() # this line return all related objects for Cart