I am writing a function to delete all the rows matching a certain query.
If I select the matching row ids, and then delete the rows with the id, in two steps, then it works. Thus I know that my query to find the rows to delete is correct:
sql = """SELECT MSN.id
FROM schedule_missingschedulenames as MSN,
names_parsedname as PN,
names_simplifiednamemapping as SNM,
names_canonicalname as CN
WHERE MSN.parsed_name_id = PN.id
AND PN.simplified_name = SNM.simplified_name
AND SNM.canonical_name_id = CN.id
AND CN.category_id = %s""" % cat.id
ids = [row.id for row in MissingScheduleNames.objects.raw(sql)]
MissingScheduleNames.objects.filter(id__in=ids).delete()
However, if I attempt to do DELETE in one query as it should, it does not work:
sql = """DELETE FROM schedule_missingschedulenames WHERE id in (SELECT MSN.id
FROM schedule_missingschedulenames as MSN,
names_parsedname as PN,
names_simplifiednamemapping as SNM,
names_canonicalname as CN
WHERE MSN.parsed_name_id = PN.id
AND PN.simplified_name = SNM.simplified_name
AND SNM.canonical_name_id = CN.id
AND CN.category_id = %s)""" % cat.id
MissingScheduleNames.objects.raw(sql)
This second query simply doesn't delete anything.
Where am I going wrong with the DELETE query?