I have two related instances that should always be created together. I'd like to do this without using signals or override the model's save()
method.
class Car(models.Mode):
make = models.CharField(max_length=32)
model = models.CharField(max_length=32)
class Meta:
unique_together = ('make', 'model',)
objects = CarManager()
class CarProfile(models.Model):
car = models.OneToOneField(Car)
last_checkup = models.DateTimeField(blank=True, null=True)
I have created a custom CarManager that overrides models.Manager.create() to ensure the creation of CarProfile when a Car is created:
class CarManager(models.Manager):
def create(self, **kwargs):
with transaction.atomic():
car = self.model(**kwargs)
car.save(force_insert=True)
CarProfile.objects.create(car=car)
return car
When I call Car.objects.create(make='Audi', model='R8')
, a new Car instance and its corresponding CarProfile is created as expected. However when I try creating a new Car using Car.objects.update_or_create(make='Audi', model='R8')
or Car.objects.get_or_create(make='Audi', model='R8')
, in both cases a Car instance is created but no corresponding CarProfile is created.
Why doesn't update_or_create
and get_or_create
produce the expected CarProfile instance when I've specified that behaviour in the custom create() method
?
It seems that both these methods are calling the create()
from QuerySet
class instead of my custom one.
BaseManager.from_queryset(QuerySet)
. I may be wrong, but it seemsfrom_queryset
and_get_queryset_methods
create an ad-hoc Class for Manager to subclass which copies over any methods inQuerySet
not defined inBaseManager
. MyCarManager
class then subclasses that ad-hoc class so I'm confused as to whycreate
is not overriding the one inQuerySet
only forupdate_and_create
andget_or_create
. – Roughneck