问题描述
我对一个我不明白的案件感到沮丧。
我有两个相关模型:
/* styles that work */
@media only screen and (min-width: 1275px){ /* styles that HALF work */ }
@media only screen and (min-width: 751px){ /* styles that work */ }
@media only screen and (min-width: 601px) { /* styles that work */ }
@media only screen and (min-width: 376px) { /* styles that work */ }
@media only screen and (max-width: 375px) { /* styles that work */ }
和:
class Course(models.Model):
code = models.CharField(max_length=10,default='')
semester = models.CharField(max_length=10,default='')
class Meta:
unique_together = [['code','semester']]
在StudentWorkSerializer中,我想将class StudentWork(models.Model):
code = models.CharField(max_length=10,default='')
course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name='student_works')
deadline = models.DateTimeField(blank=True)
字段扩展为[代码,学期]:
course
这对GET很好,例如我收到这个:
class CourseNaturalSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = ['code','semester']
class StudentWorkWithCourseSerializer(serializers.ModelSerializer):
course = CourseNaturalSerializer(read_only=True)
class Meta:
model = StudentWork
fields = ['code','course','deadline']
但这不适用于POST:
{'code': 'HW1','course': {'code': 'T101','semester': 'S20'},'deadline': '2020-09-04T23:59:00+03:00'}
在堆栈跟踪中说:
POST /studentworks json=dict(code='HW2',course={"code": "T101","semester": "S20"},deadline="2020-09-04T23:59")
所以在我看来{{code“:” T101“,” semester“:” S20“}不会反序列化到Course对象中,并且其ID没有传递给StudentWork的创建对象?
我该怎么办?
谢谢!
更新: 我被问到相关字段序列化程序上的read_only = True是否是故意的?
如果不设置,则会得到:
django.db.utils.IntegrityError: NOT NULL constraint Failed: botdb_studentwork.course_id
这使我想到它想在我创建StudentWork时为我创建一个新课程(因为代码和学期被声明为unique_together)。我不要。
如果我在POST数据中将某个学期改为S21,我得到:
'{"course":{"non_field_errors":["The fields code,semester must make a unique set."]}}'
因此,我很困惑-我无法弄清楚如何阻止它尝试创建新课程,而只是在相关领域中使用现有课程。
解决方法
您可以考虑在POST中仅传递course_id。