0

Using the django-rest-framework is it possible to retrieve content from a related field. 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'

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

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

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

1 Answer 1

3

The related name you're using on the Project class is badly named. 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'. (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.

(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'.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.