11

http://127.0.0.1:8000/app_restFramework/users/ , return text

AttributeError at /app_restFramework/users/ 'User' object has no attribute 'books'

models.py

class User(models.Model):
    username = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publisher = models.CharField(max_length=100)
    time = models.CharField(max_length=100)
    owner = models.ManyToManyField(User)

serializers.py

from app_restFramework.models import Book,User
class UserSerializer(serializers.ModelSerializer):
    books = serializers.PrimaryKeyRelatedField(many = True, read_only = True)

    class Meta:
        model = User
        fields = ('id', 'username', 'books')

views.py

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

urls.py

url(r'^app_restFramework/users/$', app_restFramework.views.UserList.as_view() ), 

1 Answer 1

18

You have not specified the related_name in the ManyToManyField. By default it will be book_set. Therefore you can do:

book_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

If you want to use books in the serializers, you can do this in the Book model:

owner = models.ManyToManyField(User, related_name="books")
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.