Search code examples
djangofiltercontrolsadmin

show only what admin add to DB django admin


Help please. There are several admins who have different rights. There is a model where they can add a product. I want to make sure that every administrator sees what they have added themselves. In the database table there is a row сreated_by. For example, I add my books to the database and another administrator adds his books. each administrator have to sees what he added. Thow do I do this?

model.py

class MyBooks(models.Model):
book = models.ForeignKey(Books, on_delete=models.CASCADE, blank=True, null=True, default=None)
fomil = models.CharField('Фомил',max_length=100, blank=True, null=True, default=None)
name= models.CharField('Ном',max_length=100, blank=True, null=True, default=None)
is_active = models.BooleanField('Ичозати таблиг (фаъол)',default=True)
created = models.DateTimeField('Санади сохташуда', auto_now_add=True, auto_now=False, )
updated = models.DateTimeField('Санади азнавшуда',auto_now_add=False, auto_now=True)

admin.py

class BooksAdmin(admin.ModelAdmin):
list_display = [field.name for field in MyBooks._meta.fields]

 def save_model(self, request, obj, form, change):
    if not obj.created_by:
        obj.created_by = request.user
    obj.save()

class Meta:
    model = MyBooks

Solution

  • Just need to override the queryset function in your ModelAdmin to filter out those that weren't created by the requesting user.

    @admin.Register(MyBooks)
    class BooksAdmin(admin.ModelAdmin):
         list_display = [field.name for field in MyBooks._meta.fields]
    
         def get_queryset(self, request):
             qs = super().get_queryset(request)
             return qs.filter(created_by=request.user)
    
        def save_model(self, request, obj, form, change):
             obj.created_by = request.user
             super().save_model(request, obj, form, change)    
    
         class Meta:
             model = MyBooks