當我嘗試在 Django 模型上執行查詢集時出現此錯誤
'AppUser' object is not subscriptable
盡管它在陳述句中正常作業,print但錯誤僅在我將其放入IF陳述句時出現
這是我的代碼:
def to_representation(self, instance):
data = super().to_representation(instance)
print("reached here") #print normaly
print(AppUser.objects.filter(mobile=instance['mobile']).exists()) #print normally (False)
if AppUser.objects.filter(mobile=instance['mobile']).exists(): # Raises an Exception
if instance.playerprofile_set.all().count() > 0:
player_profile = instance.playerprofile_set.all()[0]
data['player_profile'] = PlayerProfileSerializer(
player_profile).data
for item in Team.objects.all():
if player_profile in item.players.all():
data['team'] = TeamSerializer(item).data
if item.cap.id == player_profile.id:
data['team'] = TeamSerializer(item).data
# data["team"] = instance.
return data
更新
這是我的AppUser課:
class AppUser(models.Model):
first_name = models.CharField(max_length=33)
last_name = models.CharField(max_length=33)
mobile = models.CharField(max_length=33)
email = models.EmailField(null=True, blank=True, max_length=33)
birthdate = models.DateField(null=True, blank=True)
password = models.CharField(max_length=33)
confirm_password = models.CharField(max_length=33)
image = models.FileField(upload_to="uploads", null=True, blank=True)
main_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
generated_code = models.PositiveIntegerField(null=True, blank=True)
user_langauge = models.CharField(max_length=33, default="en")
dark_mode = models.BooleanField(default=False)
def __str__(self):
return str(self.mobile) " " str(self.first_name) " " str(self.last_name)
所以呼叫AppUser.objects.filter()應該回傳一個查詢集或空查詢集,添加時exists()應該回傳一個True或
uj5u.com熱心網友回復:
而不是計數,使用exists():
if AppUser.objects.filter(mobile=instance['mobile']).exists():
if instance.playerprofile_set.exists():
player_profile = instance.playerprofile_set.first()
count()因為它與運行非常小的查詢相比非常有效。
對于您的原始問題,無法從示例代碼中猜測出什么問題,特別是在 print 作業時,if不是。
uj5u.com熱心網友回復:
請張貼 和 的定義和AppUser功能AppUser.objects。
不知道AppUser.objects.filter回傳什么,這個問題無法回答
uj5u.com熱心網友回復:
嘗試這個:
def to_representation(self, instance):
data = super().to_representation(instance)
print("reached here") #print normaly
print(AppUser.objects.filter(mobile=instance['mobile']).count() > 0) #print normally (False)
if AppUser:
AppUser.objects.filter(mobile=instance['mobile']).count() > 0
if instance.playerprofile_set.all().count() > 0:
player_profile = instance.playerprofile_set.all()[0]
data['player_profile'] = PlayerProfileSerializer(
player_profile).data
for item in Team.objects.all():
if player_profile in item.players.all():
data['team'] = TeamSerializer(item).data
if item.cap.id == player_profile.id:
data['team'] = TeamSerializer(item).data
# data["team"] = instance.
return data
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/440193.html
