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

后端 未结 3 827
情话喂你
情话喂你 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)

提交回复
热议问题