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() ),
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With