Django gives TypeError when using len () in QuerySet

I am programming a very simple application for storing match results, and I am stuck in the following problem. When performing one of the unit tests, the following code:

listCompetition = Competition.objects.filter(compId=competitionId)
if len(listCompetition) == 0:
   #some code here
else:
   #some code here

gives the following error:

File "C:\Users\admin\workspace\project\src\bla\bla\module.py", line 222, in getMatches
   if len(listCompetition) == 0:
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 82, in __len__
   self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 286, in iterator
   obj = model(*row[index_start:aggregate_start])
TypeError: __init__() takes exactly 3 arguments (4 given)

However, if I substitute the first line of code on:

listCompetition = list(Competition.objects.filter(compId=competitionId))

then it works fine. Why is he acting in such a strange way? How is it that Django passes 4 parameters if I defined only two in the constructor of the Competition class? If this helps, here is the model definition for the Competition class:

class Competicion(MultiName):
   def __init__(self, canonicalName, compId):
      super(Competition, self).__init__(canonicalName, compId)

class MultiName(models.Model):
   entId = models.CharField(null=True, max_length=25); 
   canonicalName = models.CharField(max_length=50, primary_key=True);

   def __init__(self, canonicalName, entId=None):
      super(MultiName, self).__init__()
      self.canonicalName = canonicalName;
      self.entId = entId;

Many thanks.

+3
source share
3 answers

, , Django, __init__. - __init__? , , .

, , , Django, . tutorial, .

, :

class Competition(MultiName):
    def __init__(self, *args, **kwargs):
        if "compId" in kwargs:
            kwargs["entId"] = kwargs.pop("compId")
        super(Competition, self).__init__(*args, **kwargs)

class MultiName(models.Model):
    entId = models.CharField(null=True, max_length=25); 
    canonicalName = models.CharField(max_length=50, primary_key=True);

, .

+3

: , . Querysets - . , .

Django : , Django , , . list() Django . , .

, , Queryset.count().

+5

Instead

if len(listCompetition) == 0:

using

if listCompetition.count() == 0:

or maybe

if not listCompetition.exists():
0
source

All Articles