60
One way to handle this would be to create a new method instead of redefining get_query_set
. Something along the lines of:
class UserContactManager(models.Manager):
def for_user(self, user):
return super(UserContactManager, self).get_query_set().filter(creator=user)
class UserContact(models.Model):
[...]
objects = UserContactManager()
This allows your view to look like this:
contacts = Contact.objects.for_user(request.user)
This should help keep your view simple, and because you would be using Django’s built in features, it isn’t likely to break in the future.
6
It seems necessary to use the middleware to store the user information.
However, I’d rather not modify the default ModelManager objects
, but hook it upto a different manager, that I will use in the code, say in your case user_objects
instead of objects.
Since you will use this only within views that are @login_required
you dont need all the complex error handling in the Middleware.
Just my 2¢.
- [Django]-Handle `post_save` signal in celery
- [Django]-How to use Query Strings for filtering Querysets in Django?
- [Django]-How to make email field unique in model User from contrib.auth in Django
-1
Or even simpler and use foreign key to retrieve queryset.
If you have model like that
class HourRecord(models.Model):
created_by = ForeignKey(get_user_model(), related_name='hour_records')
You can query HourRecords
in a view by user with simply:
request.user.hour_records.all()
- [Django]-Make sure only one worker launches the apscheduler event in a pyramid web app running multiple workers
- [Django]-How do I pass template context information when using HttpResponseRedirect in Django?
- [Django]-How can I return HTTP status code 204 from a Django view?