django模型ManyToManyField字段加入

时间:2015-10-17 16:31:56

标签: django join django-models

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

现在我想要用户登录时由用户选择购物车模型的产品列表。 如何在两个模型中应用加入,以便我获得所有产品列表中的' p' Cart.product模型中的变量。感谢

1 个答案:

答案 0 :(得分:1)

王尚对模型命名是正确的。让我们使用它们。

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)

现在你可以使用这样的过滤器了。

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

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