2016-09-14 42 views
0

我有我的模型一個超類,如下:Django模塊ID變成一個元組

class BaseModel(models.Model): 
    """ BaseClass vase aksare model ha """ 

    def __init__(self, *args, **kwargs): 
     super(BaseModel, self).__init__(args, kwargs) 
     print('******> base model __init__') 

    status = models.IntegerField(default=1) 
    is_deleted = models.BooleanField(default=False) 
    create_user = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_creator_related") 
    create_date = models.DateTimeField() 
    update_date = models.DateTimeField() 
    update_user = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_updater_related") 

    class Meta: 
     abstract = True 

    def validate(self): 
     print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^base validation') 

,我有如下輪廓模型:

class Profile(BaseModel): 
    def __init__(self, *args, **kwargs): 
     super(Profile, self).__init__(args, kwargs) 

    """ User profile """ 
    user = models.OneToOneField(User, related_name='profile') 

    mobile = models.CharField(max_length=25, null=True) 
    firstname_en = models.CharField(max_length=500, null=True) 
    lastname_en = models.CharField(max_length=500, null=True) 
    gender = models.IntegerField(default=0) 
    birth_date = models.DateTimeField(null=True) 
    edu_bg = models.ForeignKey('Category', related_name="profile__edu_bg", null=True) 
    region = models.ForeignKey('Category', related_name="profile__region", null=True) 

    credit = models.DecimalField(default=0, decimal_places=6, max_digits=15) 
    key = models.TextField(null=True) 
    secret = models.TextField(null=True) 

我有一個錯誤,當我希望下面插入一個新的用戶配置:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'.

然後打印瓦爾(userprofileObject),並意識到,'id': ((), {}),但是,我還沒有設置它。當我在插入代碼中刪除__init__函數或將ID設置爲None時,問題就解決了。

有什麼想法?

我需要那些__init__,也不想設置id=None在我的代碼

回答

0

這是Django的模型是如何工作的。你不應該改變他們的方法。 這就是爲什麼

You may be tempted to customize the model by overriding the __init__ method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding __init__ , try using one of these approaches:

# Add a classmethod on the model class: 

from django.db import models 

class Book(models.Model): 
    title = models.CharField(max_length=100) 

    @classmethod 
    def create(cls, title): 
     book = cls(title=title) 
     # do something with the book 
     return book 

book = Book.create("Pride and Prejudice") 

來源https://docs.djangoproject.com/en/1.10/ref/models/instances/#django.db.models.Model

也閱讀了本Writing a __init__ function to be used in django model

+0

適用機型 –

+1

在理論上可以,所以我不能重載__init__,但你不應該。只需使用上例中的另一個類構造函數即可。 –

+0

謝謝你我的朋友。 –

相關問題