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

前端 未结 3 1410
粉色の甜心
粉色の甜心 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条回答
  •  甜味超标
    2020-11-28 23:18

    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()
    

提交回复
热议问题