2011-02-01 49 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,這可能會影響性能。如果你只需要它們全部共享一個函數,你最好將父模型聲明爲抽象的,這樣會給你相同的功能但性能更好。 – 2011-02-01 22:01:17

回答

3

,因爲你沒有進口mcif - 您進口McifModel。試試這個:

from mcif.models.mcif_model import McifModel 

class Customer(McifModel): 
    ...