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