简体   繁体   English

'super' object 没有属性 'objects' Python Django

[英]'super' object has no attribute 'objects' Python Django

you need to get the filter using the get_related_filter class method您需要使用get_related_filter class 方法获取filter

views意见

modelPath = 'Money.models'
app_model = importlib.import_module(modelPath)
cls = getattr(app_model, 'Money')
related_result = cls().get_related_filter(search_query='search_query')

models.py模型.py

class Money(models.Model):
    money = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2)   

    def get_related_filter(self, **kwargs):
        results = super(Money, self).objects.filter(Q(money__icontains=kwargs['search_query']))
        return results

    def __str__(self):
        return self.money

why gives 'super' object has no attribute 'objects' Python Django , and does not return filter为什么给出'super' object has no attribute 'objects' Python Django ,并且不返回filter

It makes no sense to work with super(Money, self) for two reasons:使用super(Money, self)没有意义,原因有两个:

  1. this proxy object will resolve to Model , but Model nor it parents have an objects attribute;此代理 object 将解析为Model ,但Model也不是它的父母有objects属性; and
  2. even if that was the case, you can only access .objects on a model class , not the instance.即使是这种情况,您也只能访问.objects上的.objects ,而不是实例。

You thus can filter with:因此,您可以过滤:

class Money(models.Model):
    money = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2)   

    def get_related_filter(self, search_query, **kwargs):
        return Money.objects.filter(money__icontains=search_query)

    def __str__(self):
        return str(self.money)

The __str__ is also supposed to return a string, not a decimal, so you should return str(self.money) , not self.money . __str__也应该返回一个字符串,而不是小数,所以你应该返回str(self.money) ,而不是self.money

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM