使用Django REST Framework创建多个相关对象

时间:2018-05-16 16:59:56

标签: django django-rest-framework

我正在使用Djago 2.0Django REST Framework

我有 contacts / models.py

的以下模型类
class Contact(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100, blank=True, null=True)
    date_of_birth = models.DateField(blank=True, null=True)

class ContactPhoneNumber(models.Model):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
    phone = models.CharField(max_length=100)
    primary = models.BooleanField(default=False)

联系人/ views.py

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated, AdminAuthenticationPermission,)

    def get_queryset(self):
        return Contact.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user)

contacts / serializers.py 定义为

class ContactPhoneNumberSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContactPhoneNumber
        fields = ('id', 'phone', 'primary', 'created', 'modified')


class ContactSerializer(serializers.HyperlinkedModelSerializer):
    phone_numbers = ContactPhoneNumberSerializer(source='contactphonenumber_set', many=True)

    user = serializers.CurrentUserDefault()

    class Meta:
        model = Contact
        fields = ('url', 'id', 'first_name', 'last_name', 'date_of_birth', 'phone_numbers')

    def create(self, validated_data):
        phone_numbers = validated_data.pop('contactphonenumber_set')
        user = validated_data.pop('user_id')
        instance = Contact.objects.create(
            user=user,
            **validated_data
        )
        for phone_data in phone_numbers:
            ContactPhoneNumber.objects.create(contact=instance, **phone_data)
        return instance

我希望能够使用新的联系人对象创建多个phone_number实例。

如何将多个带有字段phone, primary的phone_numbers与联系人数据一起传递?

1 个答案:

答案 0 :(得分:1)

您的JSON帖子正文需要如下所示:

{
    "user": 1,
    "first_name": "Anuj",
    "last_name": "TBE",
    "date_of_birth": "1990-01-01",
    "contactphonenumber_set": [
        {
            "phone": "+91999999999",
            "primary": false
        },
        {
            "phone": "+91999999993",
            "primary": true
        }
    ]
}

在这种情况下,请考虑如何处理重复项。