Santhosh
Santhosh

Reputation: 11788

Django: values: how to call model methods

I have a model:

class Parcel(models.Model):
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True)
    fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE, null=True)
    quantity = models.IntegerField()

class Fruit(models.Model):
    name = models.CharField(max_length=30)
    health_rating = models.IntegerField(null=True)

    def somemethod(self):
        if not self.health_rating:
            return 0
        else:
            return self.health_rating

Now how can get the somemethod values also in

Parcel.objects.values('fruit__name','fruit__somemethod')

Upvotes: 0

Views: 441

Answers (2)

Shubham Agrawal
Shubham Agrawal

Reputation: 427

If you are trying to get the health_rating of those fruits that are present inside parcel then

from django.db.models import Case, IntegerField, F, Value, When

Fruits.object.filter(parcel__isnull=False).annotate(
    somemethod=Case(
        When(health_rating__isnull=True, then=Value(0)),
        default=F("health_rating"),
        output_field=IntegerField()
    )
).values("name", "somemethod")

Upvotes: 0

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

You cannot use methods defined on the model class in ORM queries. But what you can do is bring the same logic of the method into your query:

from django.db.models import Case, CharField, F, Value, When


Parcel.objects.annotate(
    somemethod=Case(
        When(name="apple", then=Value('hurry')),
        default=F('name'),
        output_field=CharField(),
    )
).values('fruit__name','somemethod')

Upvotes: 1

Related Questions