我有与使用ForeignKey的项目相关的SectionInfo模型,以及与与OneToOneField的SectionInfo相关的Section2模型。如何在Projects Serializer中访问Section2数据透明度。
models.py
class Projects(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
p_name = models.CharField(max_length=100)
p_name_full = models.CharField(max_length=150)
p_creation_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True)
class SectionInfo(models.Model):
p_id = models.ForeignKey(Projects,
on_delete=models.CASCADE, related_name='sec_info', db_column='p_id')
s_name = models.CharField(max_length=200)
s_type = models.CharField(max_length=200, db_column='type')
s_length = models.IntegerField(null=True, blank=True)
class Section2(models.Model):
info_id = models.OneToOneField('rsa.SectionInfo',
on_delete=models.CASCADE, related_name='sec_2', db_column='info_id')
s_cbRestrictionEnd_1 = models.IntegerField(null=True, blank=True)
s_cbReflector_1 = models.IntegerField(null=True, blank=True)
serializer.py
class ProjectListSerializer(ModelSerializer):
sec_2 = Section2Serializer(many=True)
class Meta:
depth = 2
model = Projects
fields = [
'p_name',
'p_name_full',
'p_creation_date',
'sec_2',
]
class Section2Serializer(ModelSerializer):
sec_info = SectionInfoSerializer(read_only=True)
class Meta:
depth = 2
model = Section2
fields = [
'sec_info',
'sec_ques',
's_cbRestrictionEnd_1',
's_cbReflector_1',
]
class SectionInfoSerializer(ModelSerializer):
class Meta:
model = SectionInfo
fields = [
's_name',
's_type',
's_length',
]
这将显示以下错误:
尝试在序列化程序
sec_2
上获取字段ProjectListSerializer
的值时出现AttributeError。 序列化程序字段的名称可能不正确,并且与Projects
实例上的任何属性或键都不匹配。 原始异常文本为:'Projects'对象没有属性'sec_2'。
答案 0 :(得分:0)
Projects类和Section2并不直接相关。 删除“ sec_2”并在项目序列化程序中包含“ sec_info”,然后使用
sec_2 = Section2Serializer(many=True)
fields = [...., 'sec_2']
在SectionInfoSerializer中。