Home > Software engineering >  Using Model Manager on queryset
Using Model Manager on queryset

Time:12-20

In my admin panel i want to do some functions from my ModelManager. I have

admin.py

def change_status(modeladmin,request,queryset):
    status = queryset.change_value()
    return status

model.py

class ItemManager(models.Manager):
   @classmethod
   def change_value(cls):
       list = Item.objects.filter(value=5)
       list.update(value=6)
       return list.list_values("id", flat=True)
   

class Item(models.Model):
    name = models.TextField()
    value = models.FloatField()

    objects = ItemManager()

But i get QuerySet object has no attribute 'change_value'. But queryset is Item Queryset so why i cant use manager methods on it?

CodePudding user response:

You should change your model.py module should be like the below:

class Item(models.Model):
    name = models.TextField()
    value = models.FloatField()

    objects = ItemManager()
    class Admin:
        manager = ItemManager()

As we expect just objects to be manager, but the admin will use manager in self.Admin.manager.

Reference: Admin model manager [djangoproject-code]

  • Related