1

I have two models Parent, Child

class Parent(models.Model):
    id = models.IntegerField(...)

class Child(models.Model)
    id = models.IntegerField(...)
    parent = models.ForeignKey(Parent, ...)
    wanted = models.CharField(default="yes")

I have a queryset

parents = Parent.objects.all()

I want to annotate a char field to parents queryset which is based on Child model

get_status(obj):
    # complex function which returns string based on child onjects
    children = Child.objects.filter(parent_id = obj.id)
    if children.count() == 1:
        return 'some'
    if children.count() == 2:
        return  'thing'

I want something like this, How to send object to get_status() function.

queryset.annotate(status = Value(get_status(), output_field=CharField()))

1 Answer 1

1
from django.db.models import Count, Case, When, Value, CharField

Parent.objects.annotate(
    children=Count('child')
).annotate(
    status=Case(
        When(children__gte=2, then=Value('thing')),
        When(children=1, then=Value('some')),
        output_field=CharField()
    )
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.