У объекта 'WorkToDo' нет атрибута 'todoativity_set'
Я пишу api rest с использованием django-rest-framework, но получаю следующую ошибку:
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'.
Модели
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)
Сериализаторы
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)
Когда я делаю GET-запрос, я получаю вышеуказанную ошибку. Но если я изменю объявленное поле "activities" в WorkToDoSerializer на:
activities = ToDoActivitySerializer(source="todoativity_set", many=True, read_only=True)
Я больше не получаю ошибку, но я получаю следующий ответ:
[
{
"id": 2,
"device": 2,
"price": 100
},
{
"id": 1,
"device": 1,
"price": 200
},
{
"id": 3,
"device": 2,
"price": 300
}
]
Но я ожидаю следующего ответа:
[
{
"id": 1,
"device": 1,
"activities": [
{
"id": 1,
"price": 15
},
{
"id": 2,
"price": 10
},
],
"price": 25
}
]