这是一个Django项目,我正在try 创建一个愿望列表(多对多不会有帮助,因为我需要DateTime才能在愿望列表中获得想要的项目).

class Client(models.Model):
    name = models.CharField(max_length=100)
    user = models.ForeignKey(User, on_delete=models.CASCADE)


class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField()

class WishItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    client = models.ForeignKey(Client, related_name="wishlist", on_delete=models.CASCADE)
    added_at = models.DateTimeField(auto_now_add=True)

我能做的只是:

wishlist = Client.objects.wishlist.select_related('product').all()
wish_products = [item.product for item in wishlist]

但我需要这样的东西,没有循环,只有一个SQL查询和一行

wishlist = Client.objects.wishlist.product.all()

当我试图运行这段代码时,我得到一个错误AttributeError: 'RelatedManager' object has no attribute 'product'

推荐答案

你可以 Select .filter(…) [Django-doc],然后 Select .order_by(…) [Django-doc]:

Product.objects.filter(wishitem__client__user=my_user).order_by('wishitem__added_at')

你可以用你的WishItem跨越ManyToManyField,让查询变得更加方便:

class Client(models.Model):
    # …
    wishlist = models.ManyToManyField(
        'Product',
        through='WishItem'
    )


class Product(models.Model):
    # …
    pass

class WishItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    client = models.ForeignKey(Client, related_name='wishitems', on_delete=models.CASCADE)
    added_at = models.DateTimeField(auto_now_add=True)

然后,您可以使用以下工具进行查询:

Product.objects.filter(client__user=my_user).order_by('wishitem__added_at')

它还将使查询Client人中的.wishlist人更加方便,在Product人中,.client_set人是管理Client人的经理,而Client人的愿望 list 上有Product人.


Note:通常使用settings.AUTH_USER_MODEL [Django-doc]来表示用户模型比直接使用User model [Django-doc]更好.有关更多信息,请参阅referencing the User model section of the documentation.

Python-3.x相关问答推荐

Python网页抓取:代码输出:汤未定义

丢弃重复的索引,并在多索引数据帧中保留一个

PythonPandas READ_EXCEL空数据帧

使用数据库将文件从Sharepoint下载到文件系统

无法使用xpath关闭selenium中的弹出窗口

当条件第一次出现时将行标记为True,如果按顺序重复则标记为False

如何在当前测试中使用fixture 转换后的数据进行参数化?

python3,将整数转换为字节:对于小整数使用 to_bytes() 有哪些替代方法?

为什么不能用格式字符串 '-' 绘制点?

Python,Web 从交互式图表中抓取数据

Python 3 - 给定未知数量的类别动态地将字典嵌套到列表中

如何在 Telethon 中向机器人发送发送表情符号

如何确定一个类的元类?

使用 Python 3 按行进行分析

'~'(波浪号)运算符在 Python 中的应用

Python 解包运算符 (*)

在 Python 3 中获取所有超类

如何将 cv2.imread 匹配到 keras image.img_load 输出

Python:在 map 对象上调用列表两次

python setup.py egg_info mysqlclient