python - 当试图获取模型字段值时,我得到 DeferredAttribute 对象 Django
问题描述
你好,所以基本上我有一个跟踪点的配置文件模型。我将这些个人资料分组为学生。所以基本上在小组中,我有一个方法通过小组中的所有学生并返回一个点列表,但它的目的是 sum(),(因为我得到一个错误,我尝试了一个列表来调试)。我如何获得实际值而不是对象?这是代码:
class profil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
points = models.SmallIntegerField(default=0)
def __str__(self):
return self.user.username
def addPoints(self, amount):
self.points += amount
def subtractPoints(self, amount):
self.points -= amount
def changePoints(self, amount):
self.points += amount
class skupine(models.Model):
choices = (
('#52A2D9', 'Modra'),
('#8ec641', 'Zelena'),
('#f3c12f', 'Rumena'),
('#e2884c', 'Oranžna'),
('#f37358', 'Rdeča'),
('#b460a5', 'Vijolična')
)
teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacherToSkupina')
title = models.CharField(max_length=30)
desciption = models.CharField(max_length=120, null=True)
color = models.CharField(max_length=7, choices=choices)
students = models.ManyToManyField(profil, related_name='studentsToSkupina')
def __str__(self):
return self.title
def get_total_points(self):
return list(profil.points for items in self.students.all())
class Meta:
verbose_name_plural = "skupine"
当我调用该方法时得到什么:
>>> s.get_total_points()
[<django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>]
我想要的是:
[4,5,2,3,6,1,3]
解决方案
我假设这s
是一个skupine
类的实例。在这种情况下,如果您需要相关对象的点列表profil
,您应该执行以下操作:
def get_total_points(self):
return [student.points for student in self.students.all()]
并且,如果您需要点的总和,请使用 sum 内置函数:
def get_total_points(self):
return sum(student.points for student in self.students.all())
推荐阅读
- jmeter - 无法在 Windows 10 64 位中使用 jdk 版本 1.8.0.45 访问 Jarfile ApacheJMeter.jar Errorlevel=1
- java - 时间和/或日期的排序
- join - SSRS 查找 - 可以加入多个列
- angular - 在用于生产的 Angular 5 ng 构建命令上,我收到错误
- dotnetnuke - 如何在一个 DNN 清单文件中安装多个包?
- php - PHP 编码修正
- python - 模拟 py 文件上的属性,以返回值而不是方法
- xcode - XCTest 找不到测试包
- rx-java2 - 修改Flowable中的每个项目
- > 取决于另一个 Flowable
- > 在 RxJava 中
- python - 如何在python中从字符串转换为浮点数?