S
S
stayHARD2016-03-24 00:05:34
Django
stayHARD, 2016-03-24 00:05:34

Creating object via Serializer, ManyToMany field?

Goodnight.
How to send values ​​to ManyToMany field when posting via serializer (DRF)?
Model:

class User(AbstractEmailUser):
    target_languages = models.ManyToManyField(Language, default='en', related_name="target_language")
    biography = models.TextField(null=True, blank=True)
    location = models.CharField(max_length=2, null=True)
    objects = UserManager()

Serializer:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ['password', 'groups', 'user_permissions', 'is_superuser',
                   'is_staff']
        read_only_fields = ['date_joined', 'last_login']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
stayHARD, 2016-03-24
@stayHARD

I wrote this piece of code, but in the debugger the rest framework refuses to even enter the function.

def create(self, validated_data):
        target_languages = validated_data.pop('target_languages')
        user = User.objects.create(**validated_data)
        for target_language in target_languages:
            user.target_languages.add(get_object_or_404(Language, iso_639_1=target_language))
        user.save()
        return user

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question