"尝试在序列化程序 AssetSerializer 上获取字段 devUserId 的值时出现 KeyError。原始异常文本是:"devUserId"



models.py

class User(models.Model):
googleId = models.CharField(max_length=512, primary_key=True, default='')
imageURL = models.CharField(max_length=512, null=True)
userName = models.CharField(max_length=512, null=True)
firstName = models.CharField(max_length=512, null=True)
lastName = models.CharField(max_length=512, null=True)
#phoneNumberRegex = RegexValidator(regex=r"^+?1?d{8,15}$")
phoneNumber = models.CharField(max_length=512, null=True)
email1 = models.CharField(max_length=512, blank=False)
email2 = models.CharField(max_length=512, blank=True)
bio = models.TextField(blank=True)
planId = models.ForeignKey('primal_user.Plans',
on_delete=models.CASCADE,
default="Free")
password = models.CharField(max_length=512, null=True)
accountCreationDate = models.DateTimeField(auto_now_add=True)
coins = models.IntegerField(default=2)
assetsDownloaded = models.IntegerField(default=0)
assetsPurchased = models.IntegerField(default=0)
class Asset(models.Model):
assetId = models.CharField(max_length=20, primary_key=True)
devUserId = models.ForeignKey(User, on_delete=models.CASCADE)
keywordId = models.ForeignKey(Tags, on_delete=models.CASCADE)
assetName = models.CharField(max_length=50, null=False)
description = models.TextField(blank=True)
features = models.TextField(blank=True)
uploadedDate = models.DateField(auto_now_add=True)
typeId = models.BooleanField(default=True)
paidStatus = models.BooleanField(default=False)
price = models.IntegerField(null=True)
size = models.FloatField(null=False)
downloadCount = models.BigIntegerField(null=True)
version = models.CharField(max_length=10)

serializer.py

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class AssetSerializer(serializers.ModelSerializer):
class Meta:
model = Asset
fields = '__all__'

views.py

class UserAsset(APIView):
def get(self,request,devUserId):
try:
user = Asset.objects.filter(devUserId=devUserId).values()
serializer = AssetSerializer(user, many= True)
return Response(serializer.data)
except Asset.DoesNotExist:
raise Http404

KeyError

我是Django的初学者,所以无法弄清楚问题是什么。我试图寻找类似问题的解决方案,但无法解决问题。我遇到了属性错误,然后在AssetSerializer中输入many=True后解决了这个问题,但现在我遇到了这个KeyError。在试图找出错误时,我注意到这个错误是在执行serializer.data时抛出的。感谢您的帮助。

在您的代码中,只需要对语法进行一个小的更改。

而不是:

user = Asset.objects.filter(devUserId=devUserId).values()

写入:

user = Asset.objects.filter(devUserId=devUserId)

这应该能解决问题!

尝试user = Asset.objects.values('fieldnamehere').filter(devUserId=devUserId)

相关内容

  • 没有找到相关文章

最新更新