[Fixed]-Django model ManyToManyField field join

1👍

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()

Leave a comment