简体   繁体   English

检索Django rest框架相关字段

[英]Retrieve Django rest framework related fields

Using the django-rest-framework is it possible to retrieve content from a related field. 使用django-rest-framework可以从相关字段中检索内容。 So for example I want to create a genre list which contains all projects within it. 例如,我想创建一个流派列表,其中包含所有项目。 This is what I have but I keep on getting the error: 这是我所拥有的,但我不断得到错误:

'Genre' object has no attribute 'project_set' “类型”对象没有属性“ project_set”

models.py models.py

class Genre(models.Model):
    name = models.CharField(max_length=100, db_index=True)

class Project(models.Model):
    title = models.CharField(max_length=100, unique=True)
    genres = models.ManyToManyField(Genre, related_name='genres')

serializers.py serializers.py

class GenreSerializer(serializers.ModelSerializer):    
    project_set = serializers.ManyRelatedField()

    class Meta:
        model = Genre
        fields = ('name', 'project_set')

The related name you're using on the Project class is badly named. 您在Project类上使用的相关名称被错误命名。 That related name is how you access the set of projects related to a given genre instance. 该相关名称是您访问与给定类型实例相关的项目集的方式。 So you should be using something like related_name='projects' . 因此,您应该使用诸如related_name='projects'类的东西。 (As it is you've got it the wrong way around.) (因为它是错误的方法。)

Then make sure that your serializer class matches up with the related name you're using, so in both places project_set should then instead be projects . 然后确保您的序列化器类与您使用的相关名称匹配,因此在这两个地方project_set应该改为projects

(Alternatively you could just remove the related_name='genres' entirely and everything will work as you were expecting, as the default related_name will be 'project_set' .) (或者,您可以完全删除related_name='genres'并且一切都会按预期工作,因为默认的related_name将是'project_set' 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM