Search code examples
djangodjango-annotate

Django adding the values of reverse foreign key as field while returning


I have two models. One is Task model and other is reward model.

class Task(models.Model):
    assigned_by = models.CharField(max_length=100)

class Reward(models.Model):
    task = model.ForeignKey(Task)

Now I want to return a queryset of Task along with the reward field in it. I tried this query. search_res = Task.objects.annotate(reward='reward').

I got this error: The annotation 'reward' conflicts with a field on the model. Please tell how to solve this. I want an field reward in each task object.


Solution

  • To reach your goal with the actual models I would simply use the relations along with the task.

    Let's say you have a task (or a queryset of tasks):

    t = Task.objects.get(pk=1)
    

    or

    for t in Task.objects.all():
    

    you can get the reward like this:

    t.reward_set.first()
    

    Take care of exception in case there's no reward actually linked to the task.

    That incurs in quite an amount of queries for large datasets, so you could optimize the requests toward the DB with select_related or prefetch_related depending on your needs. Look at the Django docs for that.