簡體   English   中英

如何將模型實例分配給Django中的類屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM