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
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)