How to add element in Django QuerySet?
I have model Report and GroupReport. They have many-to-many relation. I can easily get QuerySet[GroupReport] for all GroupReport instance:
Group Name 1:
Report Name 1
Report Name 2
Group Name 2:
Report Name 2
Report Name 10
... and etc.
But i need to add entry "Total Reports" to QuerySet[GroupReport]:
Group All reports:
Report Name 1
Report Name 2
Report Name 5
... and another reports from QuerySet[Report]
I can't store group "Total Reports" in database because using object permissions for QuerySets. It is necessary to generate the group dynamically. My Serializer expect correct queryset. How can i do this?
I tried to do it something like this:
def get_queryset(self):
groups = get_objects_for_user(
user=self.request.user,
perms=view_reportgroup,
klass=ReportGroup.actived_objects,
accept_global_perms=False
)
reports = get_objects_for_user(
user=self.request.user,
perms=view_report,
klass=Report.actived_objects,
accept_global_perms=False
)
total = ReportStorage(id=None, name='Total Reports')
total.reports.set(
Report.actived_objects.filter(
Q(id__in=reports) | Q(groups__in=groups)
).distinct()
)
return (groups | total).prefetch_related(
Prefetch(
'reports',
queryset=ReportStorage.prefetch_related(
Prefetch(
'reportstorage',
queryset=super().get_queryset()
)
)
)
)
But got expected error: "needs to have a value for field 'id' bla-bla..." for total.reports.set. I was also thinking about adding ReportStorage to groups._result_cache. But I don't understand how it should look. Maybe there are more correct ways such as custom SQL, converting QuerySet to List?