我不知道如何从requests.user.id传递user_id,并在CustomerSerializer中使用它将对象保存到数据库中.错误源于这样一个事实,即user_id存在于数据库的Customer表中,但它没有显示为要在REST_FrameworkAPI前端传递的字段(只有phoneprofile_image显示).

Here is the Customer model:

class Customer(models.Model):
    phone = models.CharField(max_length=14)
    profile_image = models.ImageField(blank=True, null=True)
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Here is the ViewSet:

class CustomerViewSet(ModelViewSet):
    queryset = Customer.objects.all()
    permission_classes = [permissions.IsAdminUser]
    serializer_class = CustomerSerializer

    # Only admin users can make requests other than 'GET'
    def get_permissions(self):
        if self.request.method == 'GET':
            return [permissions.AllowAny()]
        return [permissions.IsAdminUser()]

    @action(detail=False, methods=['GET', 'PUT'])
    def me(self, request):
        customer, created = Customer.objects.get_or_create(user_id=request.user.id)
        if request.method == 'GET':
            serializer = CustomerSerializer(customer)
            return Response(serializer.data)
        elif request.method == 'PUT':
            serializer = CustomerSerializer(customer, data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data)

...and here is the Serializer:.

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ['id', 'user_id', 'profile_image', 'phone']
```python


... and when I try to save a new customer by sending a POST request to the endpoint with the following data:

```json
{
    "profile_image": "Images/image.png",
    "phone": "009293930"
}

我得到以下错误:

IntegrityError at /api/customers/
(1048, "Column 'user_id' cannot be null")
Request Method: POST
Request URL:    http://127.0.0.1:8000/api/customers/
Django Version: 4.0.6
Exception Type: IntegrityError
Exception Value:    
(1048, "Column 'user_id' cannot be null")
Exception Location: /home/caleb/.local/share/virtualenvs/Cribr-svgsjjVF/lib/python3.8/site-packages/pymysql/err.py, line 143, in raise_mysql_exception
Python Executable:  /home/caleb/.local/share/virtualenvs/Cribr-svgsjjVF/bin/python
Python Version: 3.8.10
Python Path:    
['/home/caleb/Desktop/Cribr',
 '/home/caleb/Desktop/Cribr',
 '/snap/pycharm-professional/290/plugins/python/helpers/pycharm_display',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/caleb/.local/share/virtualenvs/Cribr-svgsjjVF/lib/python3.8/site-packages',
 '/snap/pycharm-professional/290/plugins/python/helpers/pycharm_matplotlib_backend']
Server time:    Thu, 28 Jul 2022 23:38:53 +0000

我认为这里的问题在于序列化程序类没有从POST请求中获得user_id值.我try 通过上下文对象(即context={'user_id': request.user.id})将request.user.id从视图集传递给序列化程序,但我不知道如何将其添加到序列化程序传递给save方法的已验证数据中.

在这个问题上的任何帮助都将不胜感激.先谢谢你.

推荐答案

好的,我通过重写序列化程序中的Create方法设法解决了这个问题.我添加了以下内容:

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ['id', 'user_id', 'profile_image', 'phone']
        read_only_fields = ['user_id']

    
    # NEW ---------------------------------
        def create(self, validated_data):
            user = self.context['request'].user
            customer = Customer.objects.filter(user_id=user)
            if customer.exists():
                raise serializers.ValidationError(
                'Customer already exists')
            else:
                customer = Customer.objects.create(
                    user=user, **validated_data)
            return customer

现在可以很好地保存该对象.

Python相关问答推荐

查找两极rame中组之间的所有差异

用Python解密Java加密文件

启用/禁用shiny 的自动重新加载

幂集,其中每个元素可以是正或负""""

numpy.unique如何消除重复列?

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

从列表中获取n个元素,其中list [i][0]== value''

合并与拼接并举

具有相同图例 colored颜色 和标签的堆叠子图

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

如何在海上配对图中使某些标记周围的黑色边框

数据框,如果值在范围内,则获取范围和

Autocad使用pyautocad/comtypes将对象从一个图形复制到另一个图形

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

如何使用pytest在traceback中找到特定的异常

根据过滤后的牛郎星图表中的数据计算新系列

如果列包含空值,则PANAS查询不起作用

Fake pathlib.使用pyfakefs的类变量中的路径'

根据两个lambda条件筛选组并根据条件创建新列的最佳方式是什么?

在Matplotlib中通过特定的Y值而不是 colored颜色 来改变alpha/opacity