Django在序列化程序中弹出数据返回空

时间:2017-01-14 16:57:21

标签: python django api django-rest-framework

我有一个问题,尽管我传递了数据,但这条线并没有弹出任何数据......

company_data = validated_data.pop('company', None)

有没有人知道为什么我没有将任何数据传递到我的序列化程序中?提前谢谢大家! 这些是我的序列化程序的一部分...(......意味着其他部分)

class UserSerializer(serializers.ModelSerializer):
    company = CompanySerializer(required=False)
....
class Meta:
    model = User
    fields = ('id', 'email', 'username', 'password', 'first_name',
                                 'name','phone', 'company')
    extra_kwargs = {'password': {'write_only': True}}
....
def create(self, validated_data):
    profile_data = validated_data.pop('user_profile', None)

    company_data = validated_data.pop('company', None)

下一部分是我的观点的一部分......

@api_view(['GET', 'POST'])
def users_list(request):
    """
    List all users or create a new user
    """
    if request.method == 'GET' and request.user.is_superuser:
        if request.user.is_superuser:
            records = User.objects.all()
            serializers = UserSerializer(records, many=True)
            return Response(serializers.data)
        else:
            return Response(status=status.HTTP_403_FORBIDDEN)
    elif request.method == 'POST':
        mutable = request.POST._mutable
        request.POST._mutable = True
        request.data["username"] = request.data["email"]
        request.POST._mutable = mutable

        serializer = UserSerializer(data=request.data) 
        if serializer.is_valid():
            serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(
            serializer.errors, status=status.HTTP_400_BAD_REQUEST )
.....
class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('date_of_subscription', 'company_name', 'address1',
                     'address2', 'city', 'zipcode')

以下是我的模特......

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    phone = models.CharField(max_length=20)
    email_validation_token = models.CharField(max_length=100)
    forgot_password_token = models.CharField(max_length=100)
    full_name = models.CharField(max_length=100)

    rewards = models.ManyToManyField('Reward', through='UserReward')
    user = models.OneToOneField(User, related_name="user_profile")

    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.username

class Company(models.Model):
    date_of_subscription = models.CharField(max_length=100)
    company_name = models.CharField(max_length=100)
    address1 = models.CharField(max_length=100)
    address2 = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100)
    zipcode = models.CharField(max_length=100)

    user = models.OneToOneField(User, related_name="company",
                    on_delete=models.CASCADE,
                    primary_key=True)

谢谢大家!

**我知道存在缩进错误(它们来自复制/粘贴,网站上没有错误)

这也是我如何调用它,我尝试了两种方法,如果我只是传入一个字符串化的json,它会抛出一个错误。

var data = new Object();
data.name = name;
data.email = email;
data.password = password;
data.phone = phone;
data.full_name = name;
data.company = {};
data.company.date_of_subscription = output;
data.company.address1 = companyAddress1;
data.company.company_name = companyName;
data.company.address2 = companyAddress2;
data.company.city = companyCity;
data.company.zipcode = companyZipcode;

$.ajax({
    type: 'POST',
    url: 'my url',
    data: data,
    crossDomain: true,
    success: function (msg) {
    },
    error: function (request, status, error) {
    }
});

我也试过......

data.company = {"company_name":"abc", "address1":"abc", "date_of_subscription":"date", "zipcode":"your zipcode", "city":"city name"};

它正在创建用户和用户配置文件,但它不会创建公司

1 个答案:

答案 0 :(得分:0)

问题是我从未对我的对象进行过字符串化。一旦我这样做,它就完美无缺。