Yi Tian
Yi Tian

Reputation: 81

how to assign a model instance to a class property in django

thanks first!
I met a problem when using custom class,here is the code:
class definition:

class BaseCompetition:
    def __init__(self, company):
        self.company = company
class SingleLeagueCompetition(Competition):
    def __init__(self, company):
    BaseCompetition.__init__(self,company)

when using it,like this:

test_company = Company.objects.get(id=1)
sample_single = SingleLeagueCompetition(test_company)

'Company' is a model.
But I got a error when executing the code,like this:
I just don't know what's wrong...

Traceback (most recent call last):
File "/Users/littlep/myWorks/python-works/sports_with_zeal/swz/dao.py", line 32, in __init__
self.company = company
File "/Users/littlep/.pythonbrew/pythons/Python-3.4.3/lib/python3.4/site-packages/django/db/models/fields/related.py", line 639, in __set__
if instance._state.db is None:
AttributeError: 'SingleLeagueCompetition' object has no attribute '_state'

Thanks again!

Upvotes: 0

Views: 391

Answers (1)

Rajarshi Das
Rajarshi Das

Reputation: 12320

Your SingleLeagueCompetition class should inherit from BaseCompetition, like this:

class BaseCompetition:
    def __init__(self, company):
        self.company = company
class SingleLeagueCompetition(BaseCompetition):
    def __init__(self, company):
        super().__init__(company)

also instead of call constructor by using parent class BaseCompetition._init_ you can use super to bind it in child.

More reference consult: https://docs.python.org/3.4/library/functions.html#super

Upvotes: 1

Related Questions