3

I don't need nested create/update operations. I just want to write pk of created object to FK/M2M field and after creating main object get object from this FK/M2M field. Not its primary key.

For instance, I got ValueRel and Value models. This is how they are related:

class ValueRel(BaseModel):
    table = models.ForeignKey(
        Table,
        on_delete=models.PROTECT,
    )
    object_id = models.CharField(max_length=36)

    @property
    def related_object(self):
        related_model = self.table.get_model()
        related_object = related_model.objects.filter(pk=self.object_id).first()
        return related_object


class Value(BaseModel):
    profile = models.ForeignKey(
        Profile,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        related_name="app_values",
    )
    # I want to write into this field `pk` and get its object
    value_rel = models.ManyToManyField(
        ValueRel,
        blank=True,
        related_name="values",
    )
    ...

After creating ValueRel's instance and writing it to value_rel of Value's instance I want to get ValueRel's instance like object.

Actual result (JSON response from API)

"value_rel": [
   "6a740343-0d37-4e6b-ba56-0c60ac51477f"
]

Expecting this:

"value_rel": [
   {
       "pk": "6a740343-0d37-4e6b-ba56-0c60ac51477f"
       "table": "Speciality",
       "object_id": "02548144-a27d-4c17-a90b-334ccf9e1892",
       "related_object": "Information system"
   }
]

Is there a way not to adding another field just for expected object representation and get it from value_rel?

nrgx
  • 325
  • 3
  • 13
  • 1
    You need to write `ModelSerializer` for `ValueRel` model and include it in `ValueSerializer`, take a look at https://www.django-rest-framework.org/api-guide/relations/#nested-relationships – wiaterb Sep 10 '20 at 07:42
  • 1
    @wiaterb thanks for reply. I found the solution in using `to_representation` method in `ModelSerializer` with which I overrode whole API code. – nrgx Sep 17 '20 at 05:27
  • [This question](https://stackoverflow.com/q/26561640/3188737) discusses some approaches to your question. – jhselvik Sep 22 '21 at 17:27

0 Answers0