简体   繁体   中英

'super' object has no attribute 'objects' Python Django

you need to get the filter using the get_related_filter class method

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

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

It makes no sense to work with super(Money, self) for two reasons:

  1. this proxy object will resolve to Model , but Model nor it parents have an objects attribute; and
  2. even if that was the case, you can only access .objects on a model class , not the instance.

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 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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