布尔注释导致重复吗?

编程入门 行业动态 更新时间:2024-10-26 04:25:20
本文介绍了布尔注释导致重复吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试基于外键表实现基本的收藏夹"系统.

I am trying to implement a basic 'favourites' system based on a foreign key table.

假设我有以下简单模型:

Let's say I have the following simple models:

class Item(models.Model) id = models.IntegerField() class User(models.Model) id = models.IntegerField() class UserFavourites(models.Model) user = models.ForeignKey(User, related_name='user_for_fav_rel') item = models.ForeignKey(Item, related_name='item_for_fav_rel')

现在,我为商品生成以下查询集,以查看商品是否已被用户标记为收藏夹:

Now I generate the following queryset for items to see if they have been marked as a favourite by the user:

queryset = Item.objects.all() USER_ID = request.user.id queryset = queryset.annotate( favourite=Case( When( item_for_fav_rel__user__id=USER_ID, then=Value('True') ), default=Value('False'), output_field=BooleanField() ) )

所有这些都很好用,但是在响应中,如果确实收藏了该商品,我将在queryset中收到该特定商品的副本.知道如何避免这种情况吗?

All of this works great, but in the response, if the item has indeed been favourited, I receive a duplicate of that particular item in the queryset. Any idea how to avoid this?

结果SQL查询(编辑为我认为的最小示例...)

Resultant SQL Query (edited down to the minimal example I think...)

SELECT "core_item"."id", CASE WHEN "core_userfavourites"."user_id" = 1 THEN True ELSE False END AS "favourite" FROM "core_item" LEFT OUTER JOIN "core_userfavourites" ON ("core_item"."id" = "core_userfavourites"."item_id")

推荐答案

问题是,对于core_item和core_userfavorites的每种组合,您只能获得一行.似乎没有一种方法可以完全不用原始SQL来完成您要尝试的工作,但是幸运的是Django最近(1.11)添加了编写SubQuery子句的功能,您可以在此处使用

The problem is you're getting one row for each combination of core_item and core_userfavorites. There doesn't seem to be a way to do exactly what you're trying without raw SQL, but fortunately Django very recently (1.11) added the ability to write SubQuery clauses which you can use here

from django.db.models.expressions import OuterRef, Subquery queryset = Item.objects.all() USER_ID = request.user.id user_favorites = UserFavourites.objects.filter( user_id=USER_ID, item_id=OuterRef('id') )[:1].values('user_id') queryset = queryset.annotate(user_favorite=Subquery(user_favorites))

如果用户喜欢,则会在 user_favorite 字段中为您提供 user_id ,如果没有,则为 None .

This will give you the the user_id in the user_favorite field if the user has favorited it, None if they have not.

基本上,您正在编写一个子查询以从相关表中选择一个任意值.

Basically you're writing a subquery to pick an arbitrary value from the related table.

更多推荐

布尔注释导致重复吗?

本文发布于:2023-10-18 11:32:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔   注释

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!