Home > OS >  How to store important queries in Djando models itself?
How to store important queries in Djando models itself?

Time:11-13

there are couple of queries which are important and used several times in different part of application. I wounder it would be great to have a method in the Model itself to retrieve requested data as needed. tried Classmethod and instance method but as the Manager is called in the query I got below error:

AttributeError: Manager isn't accessible via ... instances

code is look like below:

class XDL(models.Model):
    name = models.CharField(max_length = 20)
    Order_Code_Description = models.CharField(max_length = 355)
    Status = models.CharField(max_length = 20)
    Supplier = models.CharField(max_length = 100)

    @classmethod
    def get_count_xdls(cls):
        return cls.objects.all() #query example

    def get_all_supps(self):
        return self.objects.all() #query example

explained in Django documentation below:

Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations

Is there a best practice to store important queries in a method somewhere in Model (or other parts)? as these queries run several time and also writing it as a method help the documentation as well.

CodePudding user response:

A customer manager is a powerful tool for code factorization and labeling complex query.

class XDLManager(models.Manager):
    pass

class XDLQuerySet(models.QuerySet):
    def supplied_by_foo(self):
        return self.filter(supplier='Foo')

class XDL(models.Model):
    objects = XDLManager.from_queryset(XDLQuerySet)()

Any methods defined in XDLManager will only be accessible behind XDL.objects, methods defined in XDLQueryset will be accesible both behind XDL.objects and any function that returns a queryset (XDL.objects.all() for instance).

XDL.objects.filter(supplier='Foo') and XDL.objects.supplied_by_foo() are equivalent

  • Related