首页 > 解决方案 > 当试图获取模型字段值时,我得到 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]

标签: pythondjangodjango-models

解决方案


我假设这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())

推荐阅读