Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework: AttributeError: 'User' object has no attribute 'books'

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() ), 
like image 437
wgf4242 Avatar asked Feb 24 '17 11:02

wgf4242


1 Answers

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")
like image 130
Evans Murithi Avatar answered Oct 23 '22 20:10

Evans Murithi