Troir1 Troir1 - 3 months ago 22
Python Question

How to copy queryset Django

I am trying to access queryset of ManyToManyField before and after saving in def save_related(self, request, form, *args, **kwargs) method.
I want to compare them and get new objects, that were added to ManyToManyField.

So, I am getting old queryset with:

def save_related(self, request, form, * args, * * kwargs):
obj = form.instance
queryset_before = obj.translations.all()
print(queryset_before)
super(WordAdmin, self).save_related(request, form, * args, * * kwargs)
print(queryset_before)


But print(queryset_before) outputs the new, updated queryset after calling super().save_related.

So:


  1. How to copy queryset, so that saving will not affect it?

  2. Or is there a way to compare old and new values of ManyToManyField more properly?


Answer

You can get lists of IDs before and after save, then compare these lists:

def save_related(self, request, form, *args, **kwargs):
    obj = form.instance
    list_before = list(obj.translations.all().values_list('pk', flat=True))
    super(WordAdmin, self).save_related(request, form, *args, ** kwargs) 
    list_after = list(obj.translations.all().values_list('pk', flat=True))
    added_ids = [x for x in list_after if x not in list_before]
    removed_ids = [y for y in list_before if y not in list_after]