类型错误:字段 'id' 需要一个数字,但得到 <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>
Posted
技术标签:
【中文标题】类型错误:字段 \'id\' 需要一个数字,但得到 <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>【英文标题】:TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>类型错误:字段 'id' 需要一个数字,但得到 <django.contrib.auth.models.AnonymousUser object at 0x048C7E90> 【发布时间】:2020-11-07 23:28:21 【问题描述】:Cannot cast AnonymousUser to int. Are you trying to use it in place of User?
当我向我的网址发出发布请求时,我不确定如何调整我的代码以停止生成此错误。我附上了我的序列化程序、视图和模型的代码。
class ActivitySessionSerializer(serializers.Serializer):
activity_name = serializers.CharField(min_length=1, max_length=100)
def create(self, validated_data):
activity, created = Activity.objects.get_or_create(name=validated_data['activity_name'],
owner=self.context['request'].user)
return ActivitySession.objects.create(activity=activity, start_time=datetime.datetime.now())
class StartSessionView(generics.CreateAPIView):
serializer_class = serializers.ActivitySessionSerializer
User = get_user_model()
class ActivityType(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Activity(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
activity_type = models.ForeignKey(ActivityType, on_delete=models.CASCADE, null=True, blank=True)
class ActivitySession(models.Model):
activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
urlpatterns = [
path('starting_session/', views.StartSessionView.as_view()),
]
我相信我通过换行解决了它
Activity.objects.get_or_create(name=validated_data['activity_name'],
owner=self.context['request'].user)
到
Activity.objects.get_or_create(name=validated_data['activity_name'],
owner=self.context['request'].user.id)
我必须专门添加 id 字段而不是总用户对象
【问题讨论】:
这能回答你的问题吗? ForeignKey to AnonymousUser 【参考方案1】:对于那些也来这里的人,一个可能的错误是(这就是我遇到的):
您可以通过
foreignkey
或reverse foreignkey
在其他地方调用匿名user
实例。
例如,在我的代码中:
-
我在
CustomView
中收到了匿名请求,如下所示:
class CustomView(RetrieveAPIView):
serializer_class = CustomSerializer
queryset =CustomModel.objects.all()
CustomView
的CustomModel
有一个反向外键-which_model
,像这样:
from django.contrib.auth import get_user_model
User = get_user_model()
class CustomModel(BaseModel):
name = models.CharField(verbose_name="Custom name", max_length=256)
class CustomRecord(BaseModel):
which_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="related user")
which_model = models.ForeignKey("CustomModel", on_delete=models.CASCADE, verbose_name="related model",related_name="user_record",)
-
为了在匿名请求中获取
CustomModel
实例的同时获取相关的CustomRecord
实例,我在CustomSerializer
中使用了SerializerMethodField
,如下所示:
class CustomSerializer(ModelSerializer):
related_user_record = SerializerMethodField(read_only=True, source="user_record")
def get_related_user_record(self, obj):
# This is where the problem is !!!!
user_record = CustomRecord.objects.filter(
which_model=obj.id, which_user=self.context["request"].user
)
if not user_record:
return None
else:
return CustomRecordSerializer(user_record.get()).data
由于我在get_related_user_record
函数中使用了self.context["request"].user
,django尝试将用户实例的id转换为int;
但是,就像@Brad Solomon 所说,匿名用户的id 或pk 为None。,这就是错误的来源。老实说,当这个错误发生时,djano 并没有很好地报告错误源。
为了解决这个问题,我在使用用户实例之前添加了一个检查,以查看它是否是匿名用户,如下所示:
def get_related_user_record(self, obj):
# check if it's an anonymous user
if not self.context["request"].user.pk:
return None
# This is where the problem is !!!!
user_record = CustomRecord.objects.filter(
which_model=obj.id, which_user=self.context["request"].user
)
if not user_record:
return None
else:
return CustomRecordSerializer(user_record.get()).data
【讨论】:
【参考方案2】:AnonymousUser
有id=None
和pk=None
,所以在这种情况下不能直接使用。相反,建议发送至create an instance of user that reflects an anonymous user。
【讨论】:
以上是关于类型错误:字段 'id' 需要一个数字,但得到 <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>的主要内容,如果未能解决你的问题,请参考以下文章
类型错误:字段 'id' 需要一个数字,但得到 <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>
获取 ValueEerror:字段 'id' 需要一个数字,但得到一个 html