0

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.

gopiariv
  • 454
  • 7
  • 9
  • Hi. Not that clear to me what you want to accomplish. Reward has a ForeignKey to Task so it is possible for a task to have multiple rewards. That said, and without annotation you'll be able to reach all the Reward objects related to a task with task.reward_set.all(), for example. – steppo May 30 '17 at 06:31
  • there will only be one reward for a task in the database. I want to add the field reward to each task object while returning the queryset. – gopiariv May 30 '17 at 06:40
  • I think you want to list down tasks and their respective rewards and you don't know how to do this? Am I right? – Sagar May 30 '17 at 07:07
  • yes. I got it now. I have to add a related_name field while defining the foreign key. – gopiariv May 30 '17 at 07:16

1 Answers1

0

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.

steppo
  • 583
  • 3
  • 20