django rest framework many to many json write

2019-08-10 00:10发布

问题:

I have a django model that has two many to many fields (phones and emails) and serializers like these:

Models:

class Phone(ValueBase): #Value base has only a value: charField
    phone_type = models.ForeignKey(PhoneType)

class Email(ValueBase):  #Value base has only a value: charField
    email_type = models.ForeignKey(EmailType)

class Contact(PolymorphicModel, EntityBase):
    name = models.CharField(max_length=100)
    display_name = models.CharField(max_length=100)
    phones = models.ManyToManyField(Phone)
    emails = models.ManyToManyField(Email)

class Person(Contact):
    prefix = models.ForeignKey(PersonPrefix, related_name='prefix')
    middlename = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    register = models.CharField(max_length=20) #OAB ou registro internacional
    nationality = models.CharField(max_length=20)
    gender = models.ForeignKey(Gender, null=True, related_name='gender')
    person_type = models.ForeignKey(PersonType, related_name='persontype')

Serializers:

class PersonSerializer(serializers.ModelSerializer):
    prefix = typebase_serializer_factory(PersonPrefix)
    person_type = typebase_serializer_factory(PersonType)
    gender = typebase_serializer_factory(Gender)
    created_on = serializers.DateTimeField(read_only=True)
    class Meta:
        model = Person
        fields = ('id', 'prefix' ,'name', 'middlename', 'lastname', 'phones', 'emails')

class PhoneSerializer(serializers.ModelSerializer): #(Email serializer is the same)
    class Meta:
        model = Phone

I'm trying to declare my many to many fields as HyperlinkedRelatedFields, ModelFields but i can't make the Person's post accept a json like this for creation:

{
    "name": "TestName",
    "lastname": "TestLast",
    "prefix": 2, #pk
    "gender": 2, #pk
    "person_type": 1, #pk
    "register": "na",
    "phones": [{"value": "551199999998"}, {"value": "551199999998"}] #many to many field
}

What i expect with this is the relationship of prefix, gender and person_type with the related ids and phones field to create all the array items in the database and associate each other.

Is it possible without writing my own seriliazer?