所以我想用序列化器创建一个反馈对象:
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'
如果我这样做,也可以。我很困惑。
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')