drf-writable-nested
drf-writable-nested copied to clipboard
Disable update_or_create for ManyToMany nested relations
Hi,
Is there a way to disable the update_or_create relation for ManyToMany relations ?
for example
models.py
from django.db import models
class Skill(models.Model):
name = models.CharField()
class Profile(models.Model):
first_name = models.CharField()
last_name = models.CharField()
skills = models.ManyToManyField(Skill)
serializers.py
from rest_framework import serializers
from drf_writable_nested import WritableNestedModelSerializer
class SkillSerializer(serializers.ModelSerializer):
url = serializers.CharField()
class Meta:
model = Skill
fields = ('pk')
class ProfileSerializer(WritableNestedModelSerializer):
skills = SkillSerializer(many=True)
class Meta:
model = Profile
fields = ('pk', 'skills', 'first_name', 'last_name')
data = {
"profile": {
"first_name": "David",
"last_name": "Hasselhoff",
"skills": [
{
"pk": 1
},
{
"pk": 14
}
]
}
}
when we send in the above data, it first creates the skills then creates the relation in the bridge table. I want it to throw an Error or just simply refuse to save any data in the database, if the skills do not already exist in the database.
Any idea how I can do that ?
how can I deal with this problem? @claytondaley @spokzers
My answer is not "official" yet, but the PR I linked is intended to let you define behavior per-nested-serializer. This should make it possible to define each nested serializers as a different combinations of get/update and/or create. If you want to use the PR (or branch on my end), I can help you with use/troubleshooting. You should start by looking at the new-style serializers in the test cases to see how they're used/different.
FWIW it occurs to me that there are no examples of GetOrCreate
since I was just replicating the existing behavior, but it's just a different mixin.
My answer is not "official" yet, but the PR I linked is intended to let you define behavior per-nested-serializer. This should make it possible to define each nested serializers as a different combinations of get/update and/or create. If you want to use the PR (or branch on my end), I can help you with use/troubleshooting. You should start by looking at the new-style serializers in the test cases to see how they're used/different.
Thank you so much! You are doing great. I only need to update my many to many to data but if i add extra dict into JSON and make the request. it turns out creating new record while updating others. I just want to make update.
@oguzhancelikarslan Did you solve this? Not sure why there's not an option to update the M2M field if it already exists.