如何修复管理器无法通过Words实例访问错误?



我想要求和所有对象(freq)名称,当我执行这段代码时,它不工作,但相反,它引发了这个错误:管理器不能通过Words实例访问

我后来真的明白了这个错误是什么意思,但我不能把解决方案。我只知道有一个叫做(aggregate)的函数,但是我不能使用它,因为我需要从执行中排除一个特定的查询。

代码是这样的:

models.py

class Words(models.Model):
freq = models.IntegerField(blank=True, null=True)
...
def sum_freq(self):
freqs = []
words = self.objects.all().exclude(tag='Pu')
for word in words:
freqs.append(word.freq)
summation = sum(freqs)
return summation

def percent_n(self):
words = self.objects.all().exclude(tag='Pu')
percent_list = []
for word in words:
percent_n = (word.freq / word.sum_freq) * 100
percent_n = round(percent_n, 2)
percent_list.append(percent_n)
return percent_list

我需要先将freq查询求和,然后返回给percent_n函数,从而将sum_freq调用到percent_n中。直到现在我才知道percent_n函数是否有效,因为我没有测试freq函数。

您不应该使用self.objects,而是Words.objectstype(self).objects:

class Words(models.Model):
# …
def sum_freq(self):
freqs = []
words =type(self).objects.all().exclude(tag='Pu')
for word in words:
freqs.append(word.freq)
summation = sum(freqs)
return summation
def percent_n(self):
words =type(self).objects.all().exclude(tag='Pu')
percent_list = []
for word in words:
percent_n = (word.freq / word.sum_freq) * 100
percent_n = round(percent_n, 2)
percent_list.append(percent_n)
return percent_list

由于sum_freqpercent_n从来没有真正处理过self对象,您可能希望通过使用@classmethod装饰器将其转换为classmethod:

class Words(models.Model):
# …
@classmethod
def sum_freq(cls):
freqs = []
words =cls.objects.exclude(tag='Pu')
for word in words:
freqs.append(word.freq)
summation = sum(freqs)
return summation
@classmethod
def percent_n(cls):
words =cls.objects.exclude(tag='Pu')
percent_list = []
for word in words:
percent_n = (word.freq / word.sum_freq) * 100
percent_n = round(percent_n, 2)
percent_list.append(percent_n)
return percent_list
也就是说,你不需要自己聚合,你可以很容易地使用Django的.aggregate(…)进行聚合。[Django-doc]:
from django.db.models importF, Sum
from django.db.models.functions importRound
class Words(models.Model):
# …
@classmethod
def sum_freq(cls):
returncls.objects.exclude(tag='Pu').aggregate(
summation=Sum('freq')
)['summation'] or 0
@classmethod
def percent_n(cls):
summation = cls.sum_freq()
return list(
cls.objects.exclude(tag='Pu').values_list(
Round(10000*F('freq')/summation)/100,
flat=True
)
)

最新更新