Home > Mobile >  PostgreSQL delete record from two joined tables based on conditions
PostgreSQL delete record from two joined tables based on conditions

Time:12-17

In my django project, with a PostgreSQL database connected i create these two models:

class Results(models.Model):
    device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL)
    proj_code = models.CharField(max_length=400)
    res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True)
    read_date = models.DateTimeField(verbose_name="Datetime of vals readings")
    unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL)


class VarsResults(models.Model):
    id = models.AutoField(primary_key=True)
    key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE)
    var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL)
    var_val = models.CharField(max_length=400, blank=True)
    var_val_conv = models.CharField(max_length=100, blank=True, null=True)
    base_byte_order = models.CharField(max_length=15)
    var_hash = models.CharField(max_length=400)
    has_error = models.BooleanField(default=False)

so VarsResults have a Foreignkey to Results, i would delete some records in both table starting from a condition based on Results, for example

DELETE RECORDS FROM RESULTS IF RESULTS read_date < VALUE

i would to automatically also delete all related records in VarsResults table. Is there a method in django ORM or directly using SQL for achieve this?

So many thanks in advance

CodePudding user response:

Since you have on_delete=models.CASCADE in your ForeignKey, whenever you delete a Results object all related VarsResults will also be deleted. You just need to delete the Results and you can do that with a single query:

Results.objects.filter(read_date__lt=value).delete()
  • Related