Django: generate queryset with duplicates

I need to make a queryset with duplicated items for testing purpose in Django, like:

<QuerySet [<MyModel: instance1>, <MyModel: instance1>, <MyModel: instance2>]>

What is the simplest way to do it?

1 answer

  • answered 2018-07-19 13:12 radoh

    You can use django's union function with all=True parameter, e.g.:

    MyModel.objects.filter(...).union(MyModel.objects.filter(...), all=True)

    Then you can use some condition that will result in a non-empty intersection, e.g.:

    MyModel.objects.filter(pk=1).union(MyModel.objects.filter(pk__in=[1, 2]), all=True)