Django custom managers - how do I return only objects created by the logged-in user?

浪子不回头ぞ 提交于 2019-11-27 03:01:34

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.

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¢.

Thank you for sharing the code. Not so good solution in terms of testability but I did not find another way to customize model managers by request object data. It would be better to have control over manager creation but Django does not allow this.

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!