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

前端 未结 3 1408
粉色の甜心
粉色の甜心 2020-11-28 22:19

I want to overwrite the custom objects model manager to only return objects a specific user created. Admin users should still return all objects using the objects model mana

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 23:25

    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.

提交回复
热议问题