You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django DRF报错:Field 'id'期望数字却获<User: ILador>原因排查

错误原因及修复方案

核心错误来源

1. username() 方法参数错误

你的Profile模型中username()方法里,self.user已经是User实例对象,但你却把它传给User.objects.get(id=self.user)的id参数——id字段期望数字类型,而你传入了User对象,这直接触发了TypeError。

2. age() 字段名错误

模型里定义的生日字段是dob,但age()方法里写成了self.birthday,运行时会触发AttributeError,这是潜在的隐性bug。

修复后的代码

Models.py 修改版

from django.db import models
from django.contrib.auth.models import User
from datetime import date
from .countries import COUNTRIES

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    # 修复username方法:直接从关联的User实例取username
    def username(self):
        return self.user.username

    setup = models.BooleanField(default=False)
    dob = models.DateField()

    # 修复age方法:将self.birthday改为self.dob
    def age(self):
        today = date.today()
        age = today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
        return age

    orgin = models.CharField(max_length=300, choices=COUNTRIES)
    lives = models.CharField(max_length=300, choices=COUNTRIES)
    bio = models.CharField(max_length=150)
    email = models.CharField(max_length=255)
    hobbies = models.CharField(max_length=225)
    image = models.ImageField(upload_to='images')

Serializers.py 优化建议

如果想更规范地序列化用户信息,可以用SerializerMethodField替代模型方法,或者直接嵌套UserSerializer:

from rest_framework import serializers
from .models import Profile
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True, 'required': True}}

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user=user)
        return user

class ProfileSerializer(serializers.ModelSerializer):
    # 用SerializerMethodField获取用户名,替代模型中的username方法
    username = serializers.SerializerMethodField()

    def get_username(self, obj):
        return obj.user.username

    class Meta:
        model = Profile
        fields = ('id', 'username', 'email', 'setup', 'dob', 'age', 'orgin', 'lives', 'bio', 'hobbies', 'image')

额外说明

  • DRF会自动将模型中的方法作为只读字段序列化,无需额外配置。
  • 修复后重启服务,访问/home/profiles/即可正常返回数据。

内容的提问来源于stack exchange,提问作者Itay Lador

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:03:22