'WorkToDo' object has no attribute 'todoativity_set'

I'm writing an api rest using django-rest-framework but I'm getting the following error:

Got AttributeError when attempting to get a value for field `activities` on serializer `WorkToDoSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `WorkToDo` instance.
Original exception text was: 'WorkToDo' object has no attribute 'todoativity_set'.

Models

class Activity(models.Model):
    name = models.CharField(max_length=200)
    client_price = models.DecimalField(decimal_places=2, max_digits=12, default=0)
    currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
    technician_price = models.DecimalField(decimal_places=2, max_digits=12, default=0)


class WorkToDo(models.Model):
    device = models.ForeignKey(Device, on_delete=models.CASCADE)
    activity = models.ManyToManyField(Activity, through="ToDoActivity", related_name="todos")
    
    price = models.FloatField(null=True, blank=True)
    

    def save(self, *args, **kwargs):
        if self.price is None or self.price == "":
            self.price = total_price(self)
        return super(WorkToDo, self).save(*args, **kwargs)


class ToDoActivity(models.Model):
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
    work_todo = models.ForeignKey(WorkToDo, on_delete=models.CASCADE)
    price = models.FloatField(null=True, blank=True)
    
    class Meta:
        unique_together = (('activity', 'work_todo',),)
    
    def save(self, *args, **kwargs):
        if self.price is None or self.price == "":
            self.price = recomended_price(self)
        return super(ToDoActivity, self).save(*args, **kwargs)

Serializers

class ToDoActivitySerializer(ModelSerializer):
    id = serializers.PrimaryKeyRelatedField(source='activity.id', read_only=False, required=True, queryset=Activity.objects.all())
    class Meta:
        model = ToDoActivity
        fields = ["id", "price"]

class WorkToDoSerializer(ModelSerializer):
    activities = ToDoActivitySerializer(source="todoativity_set", many=True)

    class Meta:
        model = WorkToDo
        fields = ["id", "device", "activities", "price", "lifting", "order"]

    def create(self, validated_data):
        instance = WorkToDo.objects.create(**validated_data)
        if "activities" in self.initial_data:
            activity_price = self.initial_data.get("activities")
            for data in activity_price:
                if "price" in data:
                    act = Activity.objects.get(id=data["id"])
                    ToDoActivity.objects.update_or_create(activity=act, work_todo=instance, defaults={"price":data["price"]})    
            instance.refresh_from_db()
            
            serializer = self.get_serializer(instance)
            return response.Response(serializer.data)

When I make a GET request I'm getting the above error. But if I change the declared "activities" field in the WorkToDoSerializer to:

activities = ToDoActivitySerializer(source="todoativity_set", many=True, read_only=True)

I don't get the error eny more but I get the following response:

[
  {
    "id": 2,
    "device": 2,
    "price": 100
  },
  {
    "id": 1,
    "device": 1,
    "price": 200
  },
  {
    "id": 3,
    "device": 2,
    "price": 300
  }
]

But I'm expecting the next respose:

[
  {
   "id": 1,
   "device": 1,
   "activities": [
       {
        "id": 1,
        "price": 15
      },
      {
        "id": 2,
        "price": 10
      },
    ],
    "price": 25
  }
]
Back to Top