django - Filter M2M in template? -
in model, have following m2m field
class familymember(abstractuser): ... email_list = models.manytomanyfield('emaillist', verbose_name="email lists", blank=true, null=true) ...
the emaillist table looks this:
class emaillist(models.model): name = models.charfield(max_length=50, default='my list') description = models.textfield(blank=true) is_active = models.booleanfield(verbose_name="active") is_managed_by_user = models.booleanfield(verbose_name="user managed")
in app, user should see records is_active=true , is_managed_by_user=true.
in admin side, admin should able add user any/all of these groups, regardless of is_active , is_managed_by_user flag.
what happens admin assigns user of email list records. then, user logs in , can see subset of list (is_active=true , is_managed_by_user=true). expected behavior. however, comes next not.
the user deselects email list item , saves record. since m2m_save first clears of m2m records before calls save() lose of records admin assigned user.
how can keep those? i've tried creating multiple lists , merging them before save, i've tried passing entire list template , hiding ones is_managed_by_user=false, , can't work.
what makes more tricky me wrapped in formset.
how go coding this? right way it? filter out records user shouldn't see in view? if so, how merge missing records before save changes user makes?
you might want try setting model manager in models.py
take care of filtering. can call filter in views.py
so:
models.py:
class emaillistqueryset(models.query.queryset): def active(self): return self.filter(is_active=true) def managed_by_user(self): return self.filter(is_managed_by_user=true) class emaillistmanager(models.manager): def get_queryset(self): return emaillistqueryset(self.model, using=self._db) def get_active(self): return self.get_queryset().active() def get_all(self): return self.get_queryset().active().managed_by_user() class emaillist(models.model): name = models.charfield(max_length=50, default='my list') description = models.textfield(blank=true) is_active = models.booleanfield(verbose_name="active") is_managed_by_user = models.booleanfield(verbose_name="user managed") objects = emaillistmanager()
views.py:
def view(request): email = emaillist.objects.get_all() return render(request, 'template.html', {'email': email})
obviously there outstanding data incorporated in example, , more welcome change variables/filters according needs. however, hope above can give idea of possibilities can try.
in views email = emaillist.objects.all().is_active().is_managed_by_user()
, loading time longer if have lot of objects in database. model manager preferred save memory. additionally, not reliant on user does, both admin , user interface have talk model directly (keeping them in sync).
note: example above typed directly answer , has not been validated in text editor. apologize if there syntax or typo errors.
Comments
Post a Comment