2016-09-14 38 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

谢谢你我的朋友。 –