如何编写 Django 模型查询来获取产品列表,其中产品是否在愿望清单中?

问题描述 投票:0回答:1

模型.py

models.py 
class Product(models.Model):
    code = models.CharField(max_length=50, default=None, null=True, blank=True, unique=True)
    name = models.CharField(max_length=100)
    category_id = models.ForeignKey(category, on_delete=models.CASCADE)   
    size_id = models.ForeignKey(size, on_delete=models.CASCADE)
    cost = models.IntegerField()
    tax_id = models.ForeignKey(Tax, on_delete=models.CASCADE)
    price = models.IntegerField()

class wishlist(models.Model):
    product_id = models.ForeignKey(Product,  on_delete=models.CASCADE, 
                                      error_messages = {'unique': 'This Product is already in exist',})
    user_id = models.ForeignKey(Account, on_delete=models.CASCADE)
    create_at = models.DateTimeField(auto_now_add=True)

我正在尝试获取所有产品,例如product.objects.all(),并检查购物车和愿望清单上是否有可用的特定产品

python django django-models
1个回答
0
投票

您的模型设置错误。
一份愿望清单可以分配给一位所有者(用户)。是的,正确使用

ForeignKey

但是 使用上面的代码,您可以将一个愿望清单仅分配给一种产品。由于您正在使用
ForeignKey
(与用户的关系相同),因此您的愿望清单不能包含多个产品。

相反,您需要使用多对多关系。因为一个心愿单可以容纳多个产品,而一个产品可以被多个心愿单持有。

class wishlist(models.Model):
    product_id = models.ManyToManyField(Product)
    user_id = models.ForeignKey(Account, on_delete=models.CASCADE)
    create_at = models.DateTimeField(auto_now_add=True)
© www.soinside.com 2019 - 2024. All rights reserved.