Check all foreign keys before delete.

271 views
Skip to first unread message

pbzRPA

unread,
Mar 24, 2011, 2:46:12 PM3/24/11
to Django users
Hi,

I am constantly running in a brick wall when it comes to deleting
records in Django. If you have one or two foreign keys it is easy to
check if they are in use, but once an application starts getting big
you can not remember which models are making use of a foreign key and
if a specific foreign key is in use.

So my question: Is there a way to check if a single model record if
being used as a foreign key in all the models in a django project? For
example:

class Stage(models.Model):
description = mo.....

class Document(models,Model):
stage = models.ForeignKey(Stage)

class Server(models.Model):
stage = models.ForeignKey(Stage)

Now when I do "stage = Stage.objects.get(pk=x)" is it possible for me
to do some like "stage.?" and get back true or false if "stage" is
being used either in Document or Server or any other class that uses
Stage as a foreign Key but also only for this 1 specific record.

All I really want to do is see if I can delete "stage" without it
effecting and other records in the database.

Thanks




Shawn Milochik

unread,
Mar 24, 2011, 2:51:48 PM3/24/11
to django...@googlegroups.com
Once you have your 'stage' instance, try this:

stage._meta.get_all_related_objects()

You can get related models dynamically and check to see if there are
actually related instances for each of them.
Play with _meta in the shell and you'll find interesting and useful things.

Despite the underscore prefix, _meta is kept pretty stable and is used
often by normal users.

Shawn

pbzRPA

unread,
Mar 24, 2011, 3:01:53 PM3/24/11
to Django users
Hit the nail on the head :) Thank you very much for the quick
response. Problem solved.

Shawn Milochik

unread,
Mar 24, 2011, 3:08:42 PM3/24/11
to django...@googlegroups.com
You're welcome.

I recommend (to any Django user) that you check out Marty Alchin's
"Pro Django."

Don't hesitate for a second because it was written in the ancient
times of Django 1.1 -- for Django to be changed enough that this book
becomes irrelevant it would take many years and drastic changes to the
internals of Django. This isn't a 'how-to' book like James Bennett's,
or a 'guide' like 'The Definitive Guide' by the BDFLs. It is a
serious, in-depth look that you don't need to use Django, but you want
to know to use Django effectively.

Shawn

pbzRPA

unread,
Mar 24, 2011, 3:48:30 PM3/24/11
to Django users
Great thanks, will definitely have a look.

Jani Tiainen

unread,
Mar 25, 2011, 5:03:02 AM3/25/11
to django...@googlegroups.com

And if you're lucky and running 1.3 version you have new option on on_delete
actions that can do it autogically.

--

Jani Tiainen

Reply all
Reply to author
Forward
0 new messages