Django DRF序列化器-插入包含外键关系的数据

时间:2018-07-24 19:01:09

标签: django-rest-framework django-serializer

我有以下型号:

class Contact(models.Model):

    class Meta:
        managed = False
        db_table = 'contact'

class ContactPhone(models.Model):
    contact = models.ForeignKey(Contact, on_delete = models.CASCADE)
    number = models.CharField(max_length = 45)
    class Meta:
        managed = False
        db_table = 'contact_phone'

此外,我有以下序列化程序:

class ContactSerializer(serializers.ModelSerializer):
    server_id = serializers.IntegerField(source='id', read_only=True)
    class Meta:
        model = Contact
        fields = '__all__'

class ContactPhoneSerializer(serializers.ModelSerializer):

    class Meta:
        model = ContactPhone
        fields = '__all__'

现在,我有一个视图,可为现有联系人插入电话号码。 输入是一个看起来像这样的json:

data = {'contact_id': 12322,
        'phones':[{'number': '89120000001'}]}

视图:

def insert_contact_phone(request):
    for record in request.data['phones']:
        data['contact_id'] = request.data['contact_id']
        serializer = ContactPhoneSerializer(data = data)
                if serializer.is_valid():
                    serializer.save()  

我最终遇到以下错误:

  

/ contacts / edit中的RelatedObjectDoesNotExist ContactPhone没有   联系人。

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

如果您为ContactPhoneSerializer中的字段指定func ISOStringToLocal(_ dateString: String) -> String { let dateFormatterGet = DateFormatter() dateFormatterGet.timeZone = TimeZone(identifier: "UTC") dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" // with seconds let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "dd-MMM-yyyy hh:mm:ss" if let date = dateFormatterGet.date(from: dateString) { return dateFormatterPrint.string(from: date) } else { dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSSZZZZZ" // with millis if let date = dateFormatterGet.date(from: dateString) { return dateFormatterPrint.string(from: date) } return "" } } print(ISOStringToLocal("2017-07-01T13:24:00+02:00")) print(ISOStringToLocal("2017-07-01T13:24:00:123+02:00")) ,则其中不包含contact_id。

因此从json输入获取的contact_id不会序列化。基本上它会被忽略,当您尝试保存并创建新的ContactPhone时-它会失败,因为它没有正确设置联系人的外键。

但是仅将contact_id添加到序列化程序的字段中并不能解决您的问题。

在您看来,我建议您改为设置联系人:

__all__

并将其传递给ContactPhoneSerializer。

答案 1 :(得分:0)

Since you are using FBV, and you are trying to create ContactPhone instances, you could do it without Serializers as,

from django.shortcuts import get_object_or_404
from .models import ContactNumber


@api_view(['GET', 'POST'])
def insert_contact_phone(request):
    if request.method == 'POST':
        contact = get_object_or_404(Contact, pk=request.data['contact_id'])
        for number in request.data['phones']:
            ContactNumber.objects.create(number=number['number'], contact=contact)
    return Response("Ok")



If you are looking for a CRUD operations on your model/table, go for ModelViewset
UPDATE-1

from rest_framework.decorators import api_view


@api_view(['GET', 'POST'])
def insert_contact_phone(request):
    serializer = ContactPhoneSerializer(data=request.data)
    serializer.is_valid(True)
    serializer.save()
    return Response("OK")

Json payload should as,

{
    "contact": 1,
    "number": "89120000001"
}