Django:TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“属性”

时间:2018-12-18 11:51:36

标签: django django-models django-views

这是我的模特

class company(models.Model):
    User = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True)
    Name = models.CharField(max_length=50,blank=False)

class group1(models.Model):
    User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    group_Name = models.CharField(max_length=32)
    Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_group') 

class ledger1(models.Model):
    User            = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    Company         = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys')

我已经做到了:

from accounting_double_entry.models import group1,ledger1

model = company
paginate_by = 10

def get_queryset(self):
    return company.objects.filter(User=self.request.user).order_by('id')

def get_context_data(self, **kwargs):
    context = super(companyListView, self).get_context_data(**kwargs)
    context['selectdates'] = selectdatefield.objects.filter(User=self.request.user)
    groupcach = group1.objects.filter(User=self.request.user, Company=company.pk,Master__group_Name__icontains='Capital A/c')
    groupcacb = groupcach.annotate(
        closing = Coalesce(Sum('ledgergroups__Closing_balance'), 0))

    groupcstcb = groupcacb.aggregate(the_sum=Coalesce(Sum('closing'), Value(0)))['the_sum']

    ledcah = ledger1.objects.filter(User=self.request.user, group1_Name__group_Name__icontains='Capital A/c')   
    ledcacb = ledcah.aggregate(the_sum=Coalesce(Sum('Closing_balance'), Value(0)))['the_sum']

    total_cacb = groupcstcb + ledcacb
    context['capital'] = total_cacb
    return context

但是出现此错误:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'property'

我只是不明白这个错误是什么意思。我只想显示所有公司的资本额...

该代码行中有错误:

        groupcach = group1.objects.filter(User=self.request.user, Company=company.pk,Master__group_Name__icontains='Capital A/c')

有人知道我的代码在做什么错吗?

1 个答案:

答案 0 :(得分:3)

变量company似乎是一个类(从行model = company开始)。您应该始终使用大写字母作为类名称(即,将模型的名称命名为Company而不是company)。

此行:

groupcach = group1.objects.filter(User=self.request.user, Company=company.pk,Master__group_Name__icontains='Capital A/c')

使用company.pk,因此pk是类company的属性字段。您尚未在任何地方定义对象company

我的建议

  • 返回重构所有代码,以遵循正确的python约定:类为CamelCased,变量,属性和函数为snake_cased。
  • 请勿混淆两者:group_NameClosing_balance是错误的。
  • related_name
  • ForeignKey应该是复数。
  • 然后重新运行代码,错误将会更加明显(company未定义)。

采用这些约定的原因是,它们使以后更容易避免错误。