[CentralOH] Counting References in Django
jep200404 at columbus.rr.com
jep200404 at columbus.rr.com
Thu Dec 20 20:24:16 CET 2012
On Tue, 11 Dec 2012 16:18:35 -0500, Eric Floehr <eric at intellovations.com> wrote:
> You might be asking that question [how many records refer to
> some arbitrary record] to see if it was ok to delete a record.
Often I am.
> There is a parameter to ForeignKey that
> allows you to specify how you want to handle deletes. The default is
> CASCADE (and it's cascade even though it will construct a PostgreSQL
> database without cascade, so if you do the same delete in raw SQL, it'll
> not work). But you can choose PROTECT, which will then do the same thing
> PostgreSQL will do by default, which is not allow you to delete an object
> that is still being referenced. You can also choose SET_NULL or
> SET_DEFAULT, which on a delete will set the referencing object's reference
> to either NULL or the default value specified. You can also pass in a
> call-back to call custom code to do whatever.
Thanks!
on_delete=PROTECT[1] avoids the need for counting references
before deleting some possibly referred to record, and allows
me to clean up the code with a Pythonic try/except.
> You might be asking that question [how many records refer to
> some arbitrary record] to see if it was ok to delete a record.
Sometimes I am not.
Sometimes I need to delete or move a regular file,
not a record, if there are no references to the record that
has information (like the path) about the file.
If I was deleting the record also, I could wrangle the
file in the else: clause of a try/except, but I retain
the record about the file, even when there are no
references to that record, so for that situation,
I still need to count references.
[1] https://docs.djangoproject.com/en/1.4/ref/models/fields/#django.db.models.ForeignKey.on_delete
More information about the CentralOH
mailing list