Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get related objects ManyToMany relationships

Tags:

python

django

I have two models:

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

I want to get all related toys to this cart. how can I do this

like image 314
I.Jokhadze Avatar asked Oct 19 '16 20:10

I.Jokhadze


1 Answers

you would use...

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
like image 126
German Alzate Avatar answered Sep 22 '22 06:09

German Alzate