Why does adding this __init__() method break my Django model?

后端 未结 3 828
情话喂你
情话喂你 2021-01-23 07:13

This question is a follow-up to one I asked earlier here.

I have a Django model as follows:

class MyModel(models.Model):
    my_field1 = models.DateTimeF         


        
相关标签:
3条回答
  • 2021-01-23 08:10

    Although, you're strongly advised to use a classmethod or a custom manager in the docs, your code would not work because you have modified the calling signature of the superclass, which should have been:

    super(MyModel, self).__init__(*args, **kwargs)
    

    You can avoid doing this by using a classmethod:

    class MyModel(models.Model):
        my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False)
        my_field2 = models.DateTimeField()
    
        @classmethod
        def sync_dates(cls, myfield1):
             my_model = cls(my_field1=myfield1, my_field2=myfield1)
             # do something with my_model
             return my_model
    

    And MyModel.sync_dates(some_date) does the trick.

    Or you could use a custom manager which is the preferred way:

    class MyModelManager(models.Manager):
        def create_with_sync_date(self, myfield1):
            my_model = self.create(my_field1=myfield1, my_field2=myfield1)
            # do something with my_model
            return my_model
    
    class MyModel(models.Model):
        my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False)
        my_field2 = models.DateTimeField()
    
        objects_synced = MyModelManager()
    

    And you can call MyModel.objects_synced.create_with_sync_date(some_date)

    0 讨论(0)
  • 2021-01-23 08:13

    You don't need to use __init__ in Django models, instead use Meta class

    class MyModel(models.Model):
        my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False)
        my_field2 = models.DateTimeField()
    
        class Meta:
            verbose_name = 'My Model'
            verbose_name_plural = 'My Models' # and so on
    
    0 讨论(0)
  • 2021-01-23 08:16

    Using init is discouraged. According to Django docs:

    https://docs.djangoproject.com/en/1.9/ref/models/instances/#creating-objects

    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")
    
    0 讨论(0)
提交回复
热议问题