Not sure what I am doing wrong here:
I tried to use QuerySet.union(), in Django 2.2.10, to combine two querysets (for the same model) inside ModelAdmin.formfield_for_manytomany(). However, when the form is saved, the entire queryset is selected, regardless of the actual selection made.
Please consider the minimal example below, based on the standard Django Article/Publication example.
from django.db import models
from django.contrib import admin
class Publication(models.Model):
pass
class Article(models.Model):
publications = models.ManyToManyField(to=Publication, blank=True)
class ArticleAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == 'publications':
# the following query makes no sense, but it shows an attempt to
# combine two separate QuerySets using QuerySet.union()
kwargs['queryset'] = Publication.objects.all().union(
Publication.objects.all())
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Publication)
admin.site.register(Article, ArticleAdmin)
The initial queryset for the publications field is filtered using formfield_for_manytomany, as described in the docs.
PLEASE NOTE: The actual query in this example makes no sense, it just returns everything, but that's not important: the point is that QuerySet.union() messes up the selection. It works normally if you remove the union().
Here's what happens when I add a new Article in the admin, without selecting any publications:
Before "Save" (nothing selected)
After "Save" (everything is selected)
No matter what I do, all options are automatically selected every time the form is saved.
Am I using QuerySet.union() the wrong way, or is this expected behavior, given the restrictions on querysets returned by QuerySet.union()?

