0

I am trying to overwrite the create method in django REST's nested serializer. I have three models Project => Network => Building. Project and Network are related via m2m and a network can contain many projects.

What I am trying to do now is to send a Network and create buildings at the same time while relating (an) already existing project(s) to the network.

What I can do successfully is: I can send a network and create buildings and also create projects. This works great like this:

if ('buildings' and 'projects') in validated_data:
        buildings = validated_data.pop("buildings")
        projects = validated_data.pop("projects")
        network, _ = Network.objects.get_or_create(**validated_data)
        for building in buildings:
            network.buildings.add(Building.objects.create(**building))
        for project in projects:
            network.projects.add(Project.objects.create(**project))
        network.save()
    else:
        network, _ = Network.objects.get_or_create(**validated_data)
        network.save()
    return network

But my problem is that I do not want to create a new project. I want to relate the network to an already existing project.

But no matter how I change the code it always tells me: project already exists when I send an existing project with my json-data. I am pretty sure that REST checks the data before and that validated data can't contain existing projects in this case. I tried overwriting validate and just return the data, but it gives me the same error. I would overwrite the update method but I assume then I can't create the buildings.

But is there a way to achieve what I want? Or is that not possible? I thought this question How assign existing, nested objects in serializer? would help me, but it also doesn't let me get around what I am describing.

I send data like this:

{
    "name": "NameOfNetwork",
    "projects": [{"project_name" : "NameOfExistingProject"}],
    "buildings": [{"name":"NameOfNon-ExistingBldg"}],
}

Help with this would be very much appreciated. Thanks in advance. Of course, I can provide more code if necessary.

EDIT: Here is my api-call:

payload = {
        "name": "...",
        "projects": [{"project_name" : "NameOfExistingProject"}],
        "buildings": [{"name":"NameOfNon-ExistingBldg"}],
    }

ep = "myendpoint"

r = requests.request("post", ep, json=payload)

Micromegas
  • 1,499
  • 2
  • 20
  • 49

0 Answers0