Question

I have a model customer. I also have a model manager for that, and i have added a class QuerySet that have certain methods. add_meta()

When i use Customers.objects.filter().add_meta() i tend to get all the meta information for the each instance. but when i use Customer.objects.get(pk=1) i can not use that meta_data() method with that.

here is my code.

Reusable manager

class CustomerManager(models.Manager):
    """A re-usable Manager to access a custom QuerySet"""

    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
        return self.model.QuerySet(self.model)

MODEL

class Project(models.Model):
    objects = ProjectManager()

    class QuerySet(QuerySet):

        def add_meta(self):
            return self.extra(
                select={"priority": "COALESCE(bm_rank, sales_rank, created_at)",
                        "size": "order_size_price*order_size_weight",
                        "revenue": "current_selling_price*order_size_weight"
                },
                order_by=["priority"])

Tried the following

Project.objects.filter(pk=5).add_meta().get().size

That didnt work

Project.objects.get(pk=5).add_meta()

Can anyone have an idea how i can still use add_meta with get and with this existing code.

Was it helpful?

Solution

You could simply add properties to your model class, as your meta information involves just some simple calculations:

class Project(models.Model):
    # your fields....


    @property
    def size(self):
        return self.order_size_price * self.order_size_weight


# now this should work for every Project instance:
project = Project.objects.get(pk=1)
print project.size

If you need to do some filtering on these "calculated" attributes you may still use your extra selects...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top