Harish
Harish

Reputation: 425

django model ManyToManyField field join

--models.py--

class Products(models.Model):
    name= models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique=True)
    price = models.IntegerField(default=100)
    image1 = models.ImageField(upload_to='static/images/home', blank=True, null=True)


class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    product = models.ManyToManyField(Products, blank=True)



--views.py--

@login_required
def cart(request):
    try:
      cart_user = Cart.objects.filter(user = request.user)
    except:
      cart_user = False

    if cart_user != False:
      j = Products.objects.filter(pk=Cart.objects.filter(user=request.user)) #Not getting results in j

now i want the list of products which is selected by user form Cart Model when he or she is logged in. how to apply join in two models so that i get all the product list in 'p' variable which is in Cart.product model. Thanks

Upvotes: 0

Views: 135

Answers (1)

Kari-Antti Kuosa
Kari-Antti Kuosa

Reputation: 376

Shang Wang was right about model naming. Let's use those.

class Product(models.Model):
    name= models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique = True)
    price = models.IntegerField(default=100)
    image1 = models.ImageField(upload_to='static/images/home',blank=True,null=True)

class Cart(models.Model):
    user = models.ForeignKey(User,null=True, blank=True)
    products = models.ManyToManyField(Product, blank=True)

Now you can use filters like this.

products = Product.objects.filter(cart__user__id=1)

carts = Cart.objects.filter(articles__name__startswith="Something").distinct()

Upvotes: 1

Related Questions