2011-02-01 9 views
0

すべてのDjangoモデルに必要な機能を記述しました。すべてのモデルを特定のクラスから継承させる最善の方法は何ですか?すべてのDjangoモデルを特定のクラスから継承させる

私が試したことはうまくいかなかった。私はこのような新しいクラス作っ:

from django.db import models 

class McifModel(models.Model): 
    pass 

をそして私は別のモデルでこれをやった:

from django.db import models, connection, transaction 
from mcif.models.mcif_model import McifModel 

class Customer(mcif.models.McifModel): 
    id = models.BigIntegerField(primary_key=True) 
    customer_number = models.CharField(unique=True, max_length=255) 
    social_security_number = models.CharField(unique=True, max_length=33) 
    name = models.CharField(unique=True, max_length=255) 
    phone = models.CharField(unique=True, max_length=255) 
    deceased = models.IntegerField(unique=True, null=True, blank=True) 
    do_not_mail = models.IntegerField(null=True, blank=True) 
    created_at = models.DateTimeField() 
    updated_at = models.DateTimeField() 

しかし、私はこのエラーを得た:

Traceback (most recent call last): 
    File "./import.py", line 6, in <module> 
    from mcif.models import GenericImport, Customer, CSVRow 
    File "/home/jason/projects/mcifdjango/mcif/models/__init__.py", line 4, in <module> 
    from mcif.models.account_address import AccountAddress 
    File "/home/jason/projects/mcifdjango/mcif/models/account_address.py", line 2, in <module> 
    from mcif.models.account import Account 
    File "/home/jason/projects/mcifdjango/mcif/models/account.py", line 2, in <module> 
    from mcif.models.customer import Customer 
    File "/home/jason/projects/mcifdjango/mcif/models/customer.py", line 4, in <module> 
    class Customer(mcif.models.McifModel): 
NameError: name 'mcif' is not defined 
+2

Djangoで継承を扱うときは注意が必要です。親クラスが抽象として宣言されていない限り、継承している子クラスを照会するたびに、データベースはパフォーマンスに影響を与える可能性のあるJOINを実行します。関数を共有するためにそれらをすべて必要とするだけの場合は、親モデルを抽象として宣言することをお勧めします。これは同じ機能を提供しますが、パフォーマンスは向上します。 –

+0

どうすればいいですか?私はGoogleの "python abstract class"を使っても明確な例は見当たりません。 (私は他の言語の抽象クラスに精通していますが、Pythonではそれは単純ではないようです。) –

+0

具体的には、Pythonで抽象クラスを抽象クラスにすることはできません。 McifModelにはメソッドがないので、何をすべきか分かりません。 –

答えて

3

インポートしなかったため、 mcif - McifModelをインポートしました。これを試してください:

from mcif.models.mcif_model import McifModel 

class Customer(McifModel): 
    ... 
関連する問題