I am using Django and have 2 tables and I want to delete records from the join.
These are simplified model definitions:
from django.db import models
class MyModelA(models.Model):
created = models.DateTimeField(null=True, blank=True)
class MyModelB(models.Model):
modela = models.OneToOneField(
MyModelA, on_delete=models.DO_NOTHING, db_constraint=False
)
created = models.DateTimeField(null=True, blank=True)
If I used SQL, I could write a DELETE statement with a join, which would delete all records that are returned by the join like this:
DELETE a, b
FROM mymodela AS a
INNER JOIN mymodelb AS b
ON a.id = b.modela_id
WHERE a.created < '<some date>'
I would like to use the Django ORM and the delete() method.
I could easily write the SELECT equivalent using:
MyModelA.objects.filter(mymodelb__isnull=False)
.filter(created__lt=<some date>)
.select_related("mymodelb")
However, when I chain the delete(), only records in MyModelA are deleted and the resulting SQL-query is something like this:
DELETE FROM mymodela WHERE mymodela.id IN (<LIST OF IDs in JOIN>)
I could of course use a different on_delete action or get the list of ids and delete the records table by table, but I would like to know: is it possible to get a DELETE a, b FROM... statement as shown above?