Issue
Sorry for this question but I'm reasonably new to Django and it's eluding me. I am updating a system (think school) with users, classes (the teachable kind), etc. I have classes from the legacy system I want to bring into the new system, and I need to limit the list by a legacy_user_id. So far, I have this in
models.py
from account.models import Profile, LegacyUser
class OldClassesManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(LegacyUser.legacy_id)
class OldInstructables(models.Model):
legacy_user_id = models.IntegerField(null=False)
name = models.CharField(max_length=100, blank=False)
[other stuff]
objects = models.Manager()
SOMETHING = OldClassesManager()
def __str__(self):
return self.name
And this in views.py
class OldClassList(ListView):
model = OldInstructables
I think my problem is that I don't know what goes where I put SOMETHING
. Any help or insight would be much appreciated.
Solution
You can not filter in the manager, or at least not without a method with a parameter, since models are (normally) request-unaware.
You can filter in the view with:
from django.contrib.auth.mixins import LoginRequiredMixin
class OldClassList(LoginRequiredMixin, ListView):
model = OldInstructables
def get_queryset(self):
return (
super().get_queryset().filter(legacy_user_id=self.request.user.legacy_id)
)
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin
mixin [Django-doc].
Note: In Django, class-based views (CBV) often have a
…View
suffix, to avoid a clash with the model names. Therefore you might consider renaming the view class toOldClassListView
, instead of.OldClassList
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.