django 如何在DRF中串行化多对多字段?

r7xajy2e  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(124)

我在models.py中有三个表:

class literature_info(models.Model):
    pmid = models.CharField(primary_key=True,max_length=25)
    publication = models.CharField(max_length=50, blank=True, null=True)
    def __str__(self):
        return self.pmid
    
class dataset_info(models.Model):
    dataset_id = models.CharField(primary_key=True,max_length=25)
    literature = models.ManyToManyField(literature_info, through='literature_dataset', blank=True)
    def __str__(self):
        return self.dataset_id

class literature_dataset(models.Model):
    literature_info = models.ForeignKey(literature_info, on_delete=models.CASCADE)
    dataset_info = models.ForeignKey(dataset_info, on_delete=models.CASCADE)

字符串
当我尝试从dataset_info表中访问文学id时,我会像这样序列化字段:

class literature_info_serializer(serializers.ModelSerializer):
    class Meta:
        model = literature_info
        fields = "__all__"

class dataset_literature_serializer(serializers.ModelSerializer):
    literature = literature_info_serializer(many=True)
    class Meta:
        model = dataset_info
        fields = ('dataset_id','literature',)


它工作得很好,我通过数据集获得了文献信息。
现在我想从literature_info表中获取文献的数据集,我尝试像这样序列化该字段:

class dataset_info_serializer(serializers.ModelSerializer):
    class Meta:
        model = dataset_info
        fields = ('dataset_id',)

class literature_dataset_serializer(serializers.ModelSerializer):
    dataset_info = dataset_info_serializer(many=True)
    class Meta:
        model = literature_info
        fields = ('pmid', 'dataset_info',)


不过,这次不行了。那么我该如何解决这个问题呢?

bcs8qyzn

bcs8qyzn1#

默认情况下,反向关系的名称是``dataset_info_set,因为您没有指定**related_name=…**[Django-doc],因此这是关系的名称:

class literature_dataset_serializer(serializers.ModelSerializer):
    dataset_info_set = dataset_info_serializer(many=True)

    class Meta:
        model = literature_info
        fields = (
            'pmid',
            'dataset_info_set',
        )

字符串

注意:Django中的模型是用 PascalCase 编写的,而不是 snake_case,所以你可能想把模型从literature_info重命名为LiteratureInfo

相关问题