Django如何在多个字段中过滤对象,而不是原始的queryset

时间:2022-10-05 13:23:44

i'm trying to filter objects in a manytomany field of a queryset and am having difficulty, most other posts seemed to address filtering the queryset based on the contents of the manytomany field whereas i need to filter the ManyToMany field itself.

我试图过滤一个queryset的许多tomany字段中的对象,但遇到了困难,大多数其他帖子似乎都是针对基于manytomany字段的内容过滤queryset的,而我需要过滤manytomany字段本身。

Models:

模型:

class IngredientsUserNeeds(models.Model):
   user = models.ForeignKey(User, blank=True, null=True)
   drinks = models.ManyToManyField(Drink)

class Drink(models.Model):
    name = models.CharField(max_length = 1000, null=True, blank=True)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)

In my ListAPI view, I start filtering by

在ListAPI视图中,我开始过滤

qs = IngredientsUserNeeds.objects.all().filter(user=user)

But after calling this, I want to filter out drinks in each object of the qs that do not belong to a particular user like,

但是在调用了这个之后,我想过滤掉那些不属于某个特定用户的问题,

qs = qs.filter(drinks=drink_object)

However, this call filters the original IngredientsUserNeeds queryset and not the items in it's ManyToMany field. How can I modify my filter so that it does not filter the queryset but rather the items in each of its object's ManyToMany Fields?

然而,这个调用过滤了原始的配料—suserneed queryset,而不是它的ManyToMany字段中的条目。如何修改过滤器,使其不过滤queryset,而是过滤其对象的ManyToMany字段中的每个条目?

Edit 1

编辑1

    for obj in qs:
        obj.drinks = obj.drinks.all().filter(user=user)

I got to this point, but it unfortunately modifies the original queryset in the database. Any suggestions so that I can retain the original queryset? This is being carried out in a Django Rest Framework ListAPIView if that helps

我已经提到了这一点,但不幸的是,它修改了数据库中的原始查询集。有什么建议可以保留原来的queryset吗?如果有帮助的话,这将在Django Rest框架ListAPIView中执行

1 个解决方案

#1


1  

something like this ?

是这样的吗?

qs = IngredientsUserNeeds.objects.filter(user=user,drinks__user=user)

#1


1  

something like this ?

是这样的吗?

qs = IngredientsUserNeeds.objects.filter(user=user,drinks__user=user)