Field ‘id’ 期望是一个数字,但收到了<User: Aditya@123>。

huangapple go评论58阅读模式
英文:

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 &#39;/&#39;.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=&#39;user&#39;)

serializers.py

from authentication.serializers import UserSerializer

class BookDetailsSerializer(ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Book_Detail
        fields = &#39;__all__&#39; 

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 &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, 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 &#39;User&#39;
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py&quot;, line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py&quot;, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py&quot;, line 671, in create
obj.save(force_insert=True, using=self.db)
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 812, in save
self.save_base(
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 863, in save_base
updated = self._save_table(
^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 1006, in _save_table
results = self._do_insert(
^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 1047, in _do_insert
return manager._insert(
^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py&quot;, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py&quot;, line 1791, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1659, in execute_sql
for sql, params in self.as_sql():
^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1583, in as_sql
value_rows = [
^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1584, in &lt;listcomp&gt;
[
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1585, in &lt;listcomp&gt;
self.prepare_value(field, self.pre_save_val(field, obj))
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1523, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\related.py&quot;, line 1144, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, line 925, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2703, in get_db_prep_value
value = self.get_prep_value(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2020, in get_prep_value
raise e.__class__(
TypeError: Field &#39;id&#39; expected a number but got &lt;User: Aditya@123&gt;.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\core\handlers\exception.py&quot;, line 56, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\core\handlers\base.py&quot;, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\views\decorators\csrf.py&quot;, line 55, in wrapped_view
return view_func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\views\generic\base.py&quot;, line 103, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py&quot;, line 509, in dispatch
response = self.handle_exception(exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py&quot;, line 469, in handle_exception
self.raise_uncaught_exception(exc)
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py&quot;, line 480, in raise_uncaught_exception
raise exc
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\views.py&quot;, line 506, in dispatch
response = handler(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\generics.py&quot;, line 242, in post
return self.create(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\mixins.py&quot;, line 19, in create
self.perform_create(serializer)
File &quot;C:\Users\Aditya Pandit\Desktop\bookmart\bookmart\sell\views.py&quot;, line 15, in perform_create
serializer.save(user_id=self.request.user)
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py&quot;, line 212, in save
self.instance = self.create(validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py&quot;, 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 &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, 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 &#39;User&#39;
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\rest_framework\serializers.py&quot;, line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py&quot;, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py&quot;, line 671, in create
obj.save(force_insert=True, using=self.db)
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 812, in save
self.save_base(
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 863, in save_base
updated = self._save_table(
^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 1006, in _save_table
results = self._do_insert(
^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\base.py&quot;, line 1047, in _do_insert
return manager._insert(
^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\manager.py&quot;, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\query.py&quot;, line 1791, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1659, in execute_sql
for sql, params in self.as_sql():
^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1583, in as_sql
value_rows = [
^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1584, in &lt;listcomp&gt;
[
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1585, in &lt;listcomp&gt;
self.prepare_value(field, self.pre_save_val(field, obj))
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\sql\compiler.py&quot;, line 1523, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\related.py&quot;, line 1144, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, line 925, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2703, in get_db_prep_value
value = self.get_prep_value(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;C:\Users\Aditya Pandit\.virtualenvs\bookmart-ugZrwS1X\Lib\site-packages\django\db\models\fields\__init__.py&quot;, line 2020, in get_prep_value
raise e.__class__(
TypeError: Field &#39;id&#39; expected a number but got &lt;User: Aditya@123&gt;.

答案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 to BookDetail.

英文:

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(&lt;b&gt;user_id=self.request.user.pk&lt;/b&gt;)
def get_queryset(self):
return Book_Detail.objects.filter(&lt;b&gt;user_id=self.request.user.pk&lt;/b&gt;)&lt;/code&gt;&lt;/pre&gt;

> 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.

huangapple
  • 本文由 发表于 2023年4月10日 22:53:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定