Django: Filter a Queryset made of unions not working

前端 未结 3 1514
一向
一向 2021-02-13 14:53

I defined 3 models related with M2M relationsships

class Suite(models.Model):
    name = models.CharField(max_length=250)
    title = models.CharField(max_length         


        
相关标签:
3条回答
  • 2021-02-13 15:23

    There is a simple solution. Just use

    self.queryset = self.queryset | <querySet you want to append>
    

    instead of

    self.queryset = self.queryset.union(<QuerySet you want to append>)
    

    Worked for me. I hope this is understandable. After this you will be able to use filter.

    0 讨论(0)
  • 2021-02-13 15:28

    I had the same issue and ended up using the union query as a subquery so that the filters could work:

    yourModelUnionSubQuerySet = YourModelQS1.union(YourModelQS2)
    yourModelUnionQuerySet = YourModel.objects.filter(id__in=yourModelUnionSubQuerySet.values('id'))
    
    0 讨论(0)
  • 2021-02-13 15:36

    As stated in django docs, only count(), order_by(), values(), values_list() and slicing of union queryset is allowed. You can't filter on union queryset.

    That means, you have to apply filters on queries before applying union on them.

    Also, you can achieve your goal without even using union():

    Suite.objects.filter(role_set__users=self.get_user(), name="energia")
    

    You may need to adjust field name in filter if you've used related_name or related_query_name in definition of suites M2M field in Role model.

    0 讨论(0)
提交回复
热议问题