django 字段“id”需要数字,但得到了“add”

ubby3x7f  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(96)

我正在做一个Django项目,我有一个用于添加PC部件的API端点,当我试图访问URL /parts/add时遇到了一个问题。我得到以下错误:

ValueError: Field 'id' expected a number but got 'add'.

这个错误似乎与我的Django模型的主键字段有关,这是一个名为“id”的自动字段。当添加新的PC部件时,我没有显式提供“id”,我希望Django自动生成它。
这是我的模型:

from django.db import models
# Create your models here.

class PCparts(models.Model):
    id = models.AutoField( primary_key=True)
    name = models.CharField(max_length=128)
    type = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    release_date = models.IntegerField()  # Unix epoch timestamp
    core_clock = models.DecimalField(max_digits=5, decimal_places=2)
    boost_clock = models.DecimalField(
        max_digits=5, decimal_places=2, null=True, blank=True)
    clock_unit = models.CharField(max_length=5)
    TDP = models.IntegerField(default=0.0)
    part_no = models.CharField(max_length=20)

    class Meta:
        ordering = ['-price']

    def __str__(self) -> str:
        return self.name

以下是我的观点

from rest_framework import status
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.db.models import Avg
from .models import PCparts
from .serializers import partSerializer  # Import the serializer class
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.db.utils import IntegrityError
# Create your views here.

def list_pc_parts(request):
    # get the optional 'type' query parameter
    part_type = request.GET.get('type', '').lower()
    # if part_type not in ['CPU', 'GPU']:
    #     return JsonResponse({"status": 1, "message": "Invalid type. Valid choices are 'CPU' and 'GPU'."}, status=status.HTTP_400_BAD_REQUEST)
    # Query PC parts based on the 'type' filter
    if part_type in ['cpu', 'gpu']:
        pc_parts = PCparts.objects.filter(type__iexact=part_type)
    else:
        pc_parts = PCparts.objects.all()

    # Serialize the PC parts data using the serializer
    serializer = partSerializer(pc_parts, many=True)

    # Calculate the average price
    average_price = pc_parts.aggregate(avg_price=Avg('price'))['avg_price']

    # Create the JSON response
    response_data = {
        'status': 0,
        'total': len(serializer.data),  # Use the serialized data
        'average_price': average_price,
        'parts': serializer.data,  # Use the serialized data
    }

    return JsonResponse(response_data)

def get_part_details(request, id):
    try:
        part = PCparts.objects.get(id=id)
    except PCparts.DoesNotExist:
        return JsonResponse({"status": 1, "message": "Part not found"}, status=status.HTTP_404_NOT_FOUND)

    serializer = partSerializer(part)

    response_data = {
        'status': '0',
        **serializer.data,
    }

    return JsonResponse(response_data)

@csrf_exempt
@require_http_methods(["PUT"])
def add_pc_part(request):
    data = request.data

    # Check if 'id' is provided in the request data
    if 'id' in request.data:
        return JsonResponse({"status": 1, "message": "'id' field is not allowed in the request data"}, status=400)

   # Check if 'type' is CPU or GPU (case-insensitive)
    part_type = data.get('type', '').lower()
    if part_type not in ['cpu', 'gpu']:
        return JsonResponse({"status": 1, "message": "Invalid type. Valid choices are 'CPU' and 'GPU'."}, status=status.HTTP_400_BAD_REQUEST)

    # Serialize the request data
    serializer = partSerializer(data=data)

    if serializer.is_valid():
        # Save the new PC Part
        serializer.save()

        # Return the response with the newly generated ID
        return JsonResponse({"status": 0, "message": "New part added", "id": serializer.data['id']}, status=status.HTTP_200_OK)
    else:
        return JsonResponse({"status": 1, "message": "Invalid data provided"}, status=status.HTTP_400_BAD_REQUEST)

@csrf_exempt
@require_http_methods(["POST"])
def update_pc_part(request, id):
    try:
        # Check if 'id' is provided in the request data
        if 'id' in request.data:
            return JsonResponse({"status": 1, "message": "'id' field is not allowed in the request data"}, status=400)

        # Deserialize the request data using the serializer
        try:
            part = PCparts.objects.get(id=id)
        except PCparts.DoesNotExist:
            return JsonResponse({"status": 1, "message": "Part not found"}, status=status.HTTP_404_NOT_FOUND)

        serializer = partSerializer(part, data=request.data, partial=True)

        # Validate the data
        if not serializer.is_valid():
            return JsonResponse({"status": 1, "message": serializer.errors}, status=400)

        # Save the updated PC Part object
        serializer.save()

        return JsonResponse({"status": 0, "message": "Part details updated"}, status=200)

    except IntegrityError:
        return JsonResponse({"status": 1, "message": "Failed to update PC Part"}, status=500)

任何帮助是赞赏感谢!!!
当我尝试访问/parts/add时出现了这个问题,它似乎与Django如何处理主键和AutoField有关。

fhity93d

fhity93d1#

这很可能是由于URL配置的原因。就像在url中传递id值一样。但是在urlpattern中,您没有提到id参数,或者您在URL中缺少id值部分。例如:-/parts/add-> /parts/<int:pc_id>/add或反之亦然

相关问题