I.Jokhadze
I.Jokhadze

Reputation: 477

Django get related objects ManyToMany relationships

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

Upvotes: 10

Views: 14296

Answers (1)

German Alzate
German Alzate

Reputation: 821

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

Upvotes: 25

Related Questions