aakash singh
aakash singh

Reputation: 305

Django delete row from table of third level foreign key

I want to delete a row from model or table where I have the foreign_key value of the row to be deleted and the value of first level table row.

For example, I have models say A, B, C where B is referring to A, C is referring to B.

class A(models.Model):
    a = models.CharFeild(max_length=10)
    b = models.CharFeild(max_length=10)
    c = models.IntegerFeild(default=1)

class B(models.Model):
    b_col = models.CharFeild(max_length=10)
    a = models.ForeignKey(A, db_index=True)
    c_col = models.IntegerFeild(default=1)

class C(models.Model):
    c_col = models.CharFeild(max_length=10)
    b = models.ForeignKey(B, db_index=True)
    d_col = models.IntegerFeild(default=1)

A
id a b c
1  x y 100
2  y z 200
.  . . . 

B
id b_col a_id c_col
1    q    1    300
2    r    2    400
.    .    .     .

C
id c_col b_id d_col
1   i      1   500 
2   j      2   600
.   .      .    .

So here i have model C column d_col value which is 600 and model A column 'c' value=200 so want to remove row from model C where c_col=200. One way is,

a = A.objects.filter(c=200)
b = B.objects.filter(a_id=a.id)
c = C.objects.filter(b_id=b.id).delete()

Is there any better way to do this in one single query instead of 3.

Upvotes: 2

Views: 1359

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

You can simply do:

C.objects.filter(b__a__c=200).delete()

Upvotes: 2

Related Questions