views:

69

answers:

1

Hi,

I have the problem that objects were unexpectedly deleted and created a minimal example. I dont't know whether it's a bug or if a made a thinking error.

The models are something like that:

class A(models.Model):
    related = models.ForeignKey('C', blank = True, null = True)

class B(models.Model):
    title = models.CharField(max_length = 255, blank = True, null = True)

class C(models.Model):
    b = models.OneToOneField('B', blank = True, null = True, related_name = 'c')

This is the test case:

a1 = A()
a1.save()

b1= B()
b1.save()

c1 = C()
c1.b = b1
c1.save()

b1 = B.objects.all()[0]
b1.c.delete()
b1.delete()

self.failUnlessEqual(A.objects.count(),1)

I deleted b1.c explicitly before deleting b1. When deleting b1.c, b1.c is NULL. It seems that then all entries of A were deleted where A.related is NULL.

Is this a bug? I really did not expect that all entries of all tables that have a NULL reference to model C are deleted.

I am using Postgres 8.4 and psycopg2 as DB Backend.

Best regards!

+1  A: 

Django implements foreign keys by default with an "ON DELETE CASCADE", which means that records pointing to a deleted record will also be deleted. It's not a bug, it's designed on purpose this way.

Workarounds are discussed elsewhere on stackoverflow.

Ivo van der Wijk
Thats right. But model A is referencing to C with "blank = True" and "null = True". And secondly it is not referencing the deleted item; the reference of A to C is NULL. My question is: Why are all records of A with a NULL reference to C are deleted when I run the given test code.
o.elias
@Ivo: I created these models and found `DEFERRABLE INITIALLY DEFERRED`. Are they the same?
Manoj Govindan