ForeignKey and delete in cascade

6 views
Skip to first unread message

asrenzo

unread,
Sep 6, 2005, 6:57:22 PM9/6/05
to Django users
Hi,

Here is my problem :

Class Map(meta.Model):
name = meta.CharField(maxlength=255)

Class City(meta.Model):
map = meta.ForeignKey(Map, null = True, blank = True)
name = meta.CharField(maxlength=255)
...

Now create a Map object : OK
Now create a City with no Map related : OK
Now update the City to refer the Map : OK
Now delte the Map : Problem

If you wan't to delete the Map, all related Cities will be delete also.
It is great when a relation can not be null but you may want to keep
Cities' informations even if you delete a Map.

What can I do ??

Regards,

Laurent

PS : I use postgresql as database server.

Adrian Holovaty

unread,
Sep 6, 2005, 8:02:17 PM9/6/05
to django...@googlegroups.com
On 9/6/05, asrenzo <laurent...@club-internet.fr> wrote:
> Here is my problem :
>
> Class Map(meta.Model):
> name = meta.CharField(maxlength=255)
>
> Class City(meta.Model):
> map = meta.ForeignKey(Map, null = True, blank = True)
> name = meta.CharField(maxlength=255)
> ...
> [..]
> If you wan't to delete the Map, all related Cities will be delete also.
> It is great when a relation can not be null but you may want to keep
> Cities' informations even if you delete a Map.

This concept is called referential integrity.

http://en.wikipedia.org/wiki/Referential_integrity

If you want to keep the Cities, edit them beforehand to set their Map to NULL.

Note that there's a longstanding ticket for a "replace relationships"
concept, which would allow an admin user to specify which value the
deleted foreignkeys should be replaced with. See
http://code.djangoproject.com/ticket/28 .

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com | chicagocrime.org

asrenzo

unread,
Sep 7, 2005, 9:48:00 AM9/7/05
to Django users
I agree with referential integrity but sometimes this way of deleting
records can mess datas also.

A simple example :

Class Team(meta.Model):
....

Class Family(meta.Model):
....

Class Person(meta.Model):
family = meta.ForeignKey(Family, null = False)
team = meta.ForeignKey(Team, null = True, blank = True)

I think that :

- if I delete a familly object, all related persons must be delete
because of the null = false statement,

- but if I delete a team, all Persons should stay because they may be
belonging to a family and that null = True.

Am I misunderstanding something ??

Reply all
Reply to author
Forward
0 new messages