Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating new objects when depth is specified in Meta class. #119

Open
aasutossh opened this issue Sep 18, 2020 · 1 comment
Open

Creating new objects when depth is specified in Meta class. #119

aasutossh opened this issue Sep 18, 2020 · 1 comment

Comments

@aasutossh
Copy link

My models:

class Snippet(models.Model):
    value = models.CharField(max_length=1000)


class List(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User, on_delete=models.CASCADE)


class ListItems(models.Model):
    snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE)
    related_list = models.ForeignKey(List, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=50)

serializers.py

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Snippet
        fields = "__all__"


class ListItemsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ListItems
        fields = "__all__"
        depth = 2


class ListSerializer(WritableNestedModelSerializer):
    listitems_set = ListItemsSerializer(many=True)
    class Meta:
        model = List
        fields = "__all__"

views.py

class SnippetViewSet(viewsets.ModelViewSet):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


class ListViewSet(viewsets.ModelViewSet):
    queryset = List.objects.all()
    serializer_class = ListSerializer


class ListItemsViewSet(viewsets.ModelViewSet):
    queryset = ListItems.objects.all()
    serializer_class = ListItemsSerializer

POSTing data like these to ListSerializer:

{
  "listitems_set": [
    {
      "name": "item5",
      "snippet": 1
    },
    {
      "name": "item6",
      "snippet": 1
    }
  ],
    "name": "Third List",
    "user": 1
}

results in error

IntegrityError at /list/
NOT NULL constraint failed: list_listitems.snippet_id

But the List is created without the listitem_set.
If I comment out depth=2 in the ListItemsSerializer it works fine.

I've enabled the depth option because I get all the related data at once, instead of fetching each and every data manually.

Let me know if something is unclear, or if I've made a mistake.

@ruscoder
Copy link
Member

Hello @aasutossh! I believe this case wasn't covered in this library yet. As a workaround, I can suggest you implement two serializers: the first for creating/updating and the second for reading.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants