使用序列化程序用外键创建对象

问题描述 投票:0回答:1

所以我想用序列化器创建一个反馈对象:

class Location(models.Model):
    name = models.CharField(max_length=256)
    img_small = models.CharField(max_length=1024, blank=True, null=True)
    img_large = models.CharField(max_length=1024, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'location'

class Schedules(models.Model):
    user = models.ForeignKey(Users, models.DO_NOTHING, default=None)
    name = models.CharField(max_length=512, blank=True, null=True)
    location = models.ForeignKey(Location, models.DO_NOTHING, default=None)
    detail = models.TextField(blank=True, null=True)
    start = models.DateField()
    end = models.DateField()
    created = models.DateTimeField(blank=True, null=True)
    modified = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'schedules'

class Feedbacks(models.Model):
    location = models.ForeignKey(Location, models.DO_NOTHING)
    schedule = models.ForeignKey(Schedules, models.DO_NOTHING)
    start = models.IntegerField(blank=True, null=True)
    end = models.IntegerField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True)
    modified = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'feedbacks'

和序列化程序类:

class FeedbackSerializer(serializers.ModelSerializer):
    location_id = serializers.PrimaryKeyRelatedField(queryset=Location.objects.all())
    schedule_id = serializers.PrimaryKeyRelatedField(queryset=Schedules.objects.all())
    class Meta:
        model = Feedbacks
        fields = ('location_id', 'schedule_id', 'start', 'end')
        # read_only_fields = ('location_id', 'schedule_id')

我的数据是

{"location_id" : 2, "schedule_id" : 2, "start" : "1", "end" : 2}

问题是,在验证之后,我的validated_data包含Location和Schedule对象,而不是ID,因此我无法插入并得到此错误

int() argument must be a string, a bytes-like object or a number, not 'Location'
django django-rest-framework django-serializer
1个回答
0
投票

如果我这样做,也可以。我很困惑。

class FeedbackSerializer(serializers.ModelSerializer):
    location = serializers.PrimaryKeyRelatedField(queryset=Location.objects.all())
    schedule = serializers.PrimaryKeyRelatedField(queryset=Schedules.objects.all())
    class Meta:
        model = Feedbacks
        fields = ('location', 'schedule', 'start', 'end')

© www.soinside.com 2019 - 2024. All rights reserved.