![](/img/trans.png)
[英]Django - how to assign custom object as model property and get that model instance in that object?
[英]how to assign a model instance to a class property in django
首先謝謝!
使用自定義類時遇到問題,代碼如下:
類定義:
class BaseCompetition:
def __init__(self, company):
self.company = company
class SingleLeagueCompetition(Competition):
def __init__(self, company):
BaseCompetition.__init__(self,company)
使用時,如下所示:
test_company = Company.objects.get(id=1)
sample_single = SingleLeagueCompetition(test_company)
“公司”是一個典范。
但是執行代碼時出現錯誤,如下所示:
我只是不知道怎么了...
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'
再次感謝!
您的SingleLeagueCompetition
類應繼承自BaseCompetition
,如下所示:
class BaseCompetition:
def __init__(self, company):
self.company = company
class SingleLeagueCompetition(BaseCompetition):
def __init__(self, company):
super().__init__(company)
也可以通過使用super
將其綁定到子級中,而不是使用父類BaseCompetition._init_
來調用構造函數。
更多參考資料請咨詢: https : //docs.python.org/3.4/library/functions.html#super
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.