Django模型中的外键属性没有被反序列化

时间:2016-07-11 07:20:24

标签: python django django-models django-rest-framework deserialization

我正在尝试序列化模型的外键元素,但是当我反序列化对象时,我没有在validated_data列表中获取外键条目。

雇主应用程序的 models.py 如下:

from django.db import models
from django.conf import settings
from datetime import datetime
from django.contrib import admin


class Employer(models.Model):

entity = models.ForeignKey('entities.Entity',
related_name='employers_ent', null=True,blank=True)
profile = models.OneToOneField(settings.AUTH_USER_MODEL)
ROLE = (
    ('1', 'Admin'),
    ('2', 'Manager'),)
employer_role = models.CharField(max_length=2,  choices=ROLE, default='1')
name = models.CharField(max_length= 500, null=True,blank=True)
email = models.CharField(max_length= 500, null=True,blank=True)
contact_number = models.IntegerField(null=True,blank=True)

我从中调用EmployerSerializer的views.py是 - >

@login_required
@api_view(['GET', 'POST'])
def employers_list(request):
    if request.method == 'GET':
        employers = Employer.objects.all()
        employer_serializer = EmployerSerializer(employers, many=True)
        return Response(employer_serializer.data)

    elif request.method == 'POST':
        print "I am here yay"
        data = JSONParser().parse(request)
        data['username']=request.user.username
        try:
            e = Entity.objects.get(company_name=data['entity'])
            e.save()
            data['entity']= e
        except Exception as e:
            e , created = Entity.objects.update_or_create(company_name=data['entity'])
            e.save()
            data['entity']=e
        employer_serializer = EmployerSerializer(data=data)
        print employer_serializer
        print employer_serializer.is_valid()
        if employer_serializer.is_valid():
            employer_serializer.save()
            return Response(employer_serializer.data, status=status.HTTP_201_CREATED)
        return Response(employer_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

雇主应用程序的serializers.py看起来像:

from app.employers.models import Employer
from rest_framework import serializers
from app.accounts.models import User
from django.core.mail import EmailMultiAlternatives
from app.entities.serializers import EntitySerializer
import logging

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)


class EmployerSerializer(serializers.ModelSerializer):
    print "here I am "

    id = serializers.IntegerField(source='pk', read_only = True)
    username = serializers.CharField(source='profile.username')
    entity = serializers.ReadOnlyField(source='entity.company_name')
    # employer_role = serializers.CharField(default='1')

    class Meta:
        print("This is me")
        model = Employer
        entity = serializers.StringRelatedField(many=True)
        fields = ('id', 'username', 'employer_role', 'name', 'contact_number','entity', 'email')

    def update(self, instance, validated_data):

        print("I have come into the world")
        instance.name = validated_data.get('name', instance.name)
        instance.contact_number = validated_data.get('contact_number', instance.contact_number)
        instance.email = validated_data.get('email', instance.email)
        instance.employer_role = validated_data.get('employer_role', instance.employer_role)

        instance.save()
        print instance

        return instance

    def create(self, validated_data):
        print ("wild and free")
        user_data = validated_data.pop('profile')
        username = user_data['username']
        log.info(validated_data)
        user = User.objects.get(username=username)

        if user is not None:
            profile = Employer.objects.create(profile=user, **validated_data)

            return profile

我收到的回复如下: {"id":24,"username":"subhajitm6@gmail.com","employer_role":"1","name":"Uhyres","contact_number":1111,"entity":null,"email":"admin@textnook.in"}

如何解决此问题并获得entity字段的正确回复。有人可以帮帮我吗。谢谢。

0 个答案:

没有答案