简体   繁体   中英

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!

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

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