英文:
Field 'id' expected a number but got <User: Aditya@123>
问题
I am using nested serializer for Django user module and BookDetail where user is Foreign key in BookDetail model. For perform_create method I am getting this error. Instead of considering id, self.request.user is considering username
class BookDetailsList(ListCreateAPIView):
serializer_class = BookDetailsSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
def get_queryset(self):
return Book_Detail.objects.filter(user_id=self.request.user)
I tried different ways to get id but I am always getting <User: Aditya@123>. I am expecting to get User Model "id" in perform_create method
models.py
from django.db import models
from django.contrib.auth.models import User
class Book_Detail(models.Model):
# ...
user = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='user')
serializers.py
from authentication.serializers import UserSerializer
class BookDetailsSerializer(ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Book_Detail
fields = '__all__'
view.py
from .models import Book_Detail
from .serializers import BookDetailsSerializer
from rest_framework import permissions
class BookDetailsList(ListCreateAPIView):
serializer_class = BookDetailsSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
def get_queryset(self):
return Book_Detail.objects.filter(user_id=self.request.user)
I am getting this error
Internal Server Error: /api/sell/
Traceback (most recent call last):
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2018, in get_prep_value
return int(value)
^^^^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'User'
# ... (rest of the error traceback)
The error is related to the user
field in your serializer. You may need to adjust your serializer or model to correctly save the user ID.
英文:
I am using nested serializer for Django user module and BookDetail where user is Foreign key in BookDetail model. For perform_create method I am getting this error. Instead of considering id, self.request.user is considering username
class BookDetailsList(ListCreateAPIView):
serializer_class = BookDetailsSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
def get_queryset(self):
return Book_Detail.objects.filter(user_id=self.request.user)
I tried different ways to get id but I am always getting <User: Aditya@123>. I am expecting to get User Model "id" in perform_create method
models.py
from django.db import models
from django.contrib.auth.models import User
class Book_Detail(models.Model):
def nameFile(instance, filename):
user = User.objects.get(username=instance.user_id)
return '/'.join([str(user.username), filename])
book_isbn = models.CharField(max_length=15)
book_name = models.CharField(max_length=255)
book_page = models.IntegerField()
book_medium = models.CharField(max_length=20)
book_author = models.CharField(max_length=255)
book_genre = models.CharField(max_length=20)
book_cover_page = models.ImageField(upload_to=nameFile, blank=True)
book_last_page = models.ImageField(upload_to=nameFile, blank=True)
book_page1 = models.ImageField(upload_to=nameFile, blank=True)
book_page2 = models.ImageField(upload_to=nameFile, blank=True)
book_page3 = models.ImageField(upload_to=nameFile, blank=True)
book_rental = models.CharField(max_length=20, null=True, blank=True)
book_price = models.FloatField()
book_description = models.TextField(null=True, blank=True)
status = models.CharField(max_length=45)
posted_date = models.DateField(null=True)
user = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='user')
serializers.py
from authentication.serializers import UserSerializer
class BookDetailsSerializer(ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Book_Detail
fields = '__all__'
view.py
from .models import Book_Detail
from .serializers import BookDetailsSerializer
from rest_framework import permissions
class BookDetailsList(ListCreateAPIView):
serializer_class = BookDetailsSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
def get_queryset(self):
return Book_Detail.objects.filter(user_id=self.request.user)
I am getting this error
Internal Server Error: /api/sell/
Traceback (most recent call last):
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2018, in get_prep_value
return int(value)
^^^^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'User'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py", line 671, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 812, in save
self.save_base(
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 863, in save_base
updated = self._save_table(
^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 1006, in _save_table
results = self._do_insert(
^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 1047, in _do_insert
return manager._insert(
^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py", line 1791, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1659, in execute_sql
for sql, params in self.as_sql():
^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1583, in as_sql
value_rows = [
^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1584, in <listcomp>
[
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1585, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1523, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\related.py", line 1144, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 925, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2703, in get_db_prep_value
value = self.get_prep_value(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2020, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <User: Aditya@123>.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\views\decorators\csrf.py", line 55, in wrapped_view
return view_func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\views\generic\base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\generics.py", line 242, in post
return self.create(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "C:\Users\Aditya Pandit\Desktop\bookmart\bookmart\sell\views.py", line 15, in perform_create
serializer.save(user_id=self.request.user)
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py", line 981, in create
raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Book_Detail.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Book_Detail.objects.create()`. You may need to make the field read-only, or override the BookDetailsSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2018, in get_prep_value
return int(value)
^^^^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'User'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py", line 671, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 812, in save
self.save_base(
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 863, in save_base
updated = self._save_table(
^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 1006, in _save_table
results = self._do_insert(
^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py", line 1047, in _do_insert
return manager._insert(
^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py", line 1791, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1659, in execute_sql
for sql, params in self.as_sql():
^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1583, in as_sql
value_rows = [
^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1584, in <listcomp>
[
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1585, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py", line 1523, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\related.py", line 1144, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 925, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2703, in get_db_prep_value
value = self.get_prep_value(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py", line 2020, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <User: Aditya@123>.
答案1
得分: 2
user_id
是一个特殊术语,表示用户的字面主键,但 request.user
是用户对象。
有两种方法可以实现这一点:
使用对象
# 没有 _id
serializer.save(user=self.request.user)
使用主键
# user.pk
serializer.save(user_id=self.request.user.pk)
编辑
只是为了澄清,这个 _id
关键字适用于所有外键:{field}_id
英文:
user_id
is a special term which means the literal PK of User, but request.user is the User object
Two ways you can do this:
Using the object
# No _id
serializer.save(user=self.request.user)
Using the PK
# user.pk
serializer.save(user_id=self.request.user.pk)
Edit
Just to clarify, this _id
keyword works for all ForeignKeys: {field}_id
答案2
得分: 0
For both filtering and creating, you use the primary key of the user:
class BookDetailsList(ListCreateAPIView):
serializer_class = BookDetailsSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user_id=self.request.user.pk)
def get_queryset(self):
return BookDetail.objects.filter(user_id=self.request.user.pk)
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
Book_Detail
toBookDetail
.
英文:
For both filtering and creating, you use the primary key of the user:
<pre><code>class BookDetailsList(ListCreateAPIView):
serializer_class = BookDetailsSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(<b>user_id=self.request.user.pk</b>)
def get_queryset(self):
return Book_Detail.objects.filter(<b>user_id=self.request.user.pk</b>)</code></pre>
> Note: Models in Django are written in PascalCase, not snake_case,
> so you might want to rename the model from <s>Book_Detail
</s> to BookDetail
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论