Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a generic.GenericForeignKey() field be Null?

I am creating an object which tracks changes (Updates) regarding the creation, updating and deletion of other so called UUIDSyncable objects in the database.

This involves any object which extends the UUIDSyncable classes's save() and delete() methods being overriden, in such a way that it creates a new Update object recording the action (either insert, update or delete) and originally a models.CharField(max_length=64) field specifying the UUID pk of of the of UUIDSyncable objects.

At this point I wanted to update the implementation to use Django's generic.GenericForeignKey() field in stead of my single character field. This would enable be to access the object about which the update is being recorded in a much simpler way.

My problem arrises when you wish to delete an object and store that as an Update object, as you know Django preforms a cascade delete on the UUIDSyncable object being deleted, deleting all the previous Update records (which is not wanted).

When the UUIDSyncable object has been deleted in my original implementation, each Update object would still retain the UUID to inform external parties about its deletion. My first solution to emulate this was to set content_object = None just before deleting the object on all the Update objects, thus preventing the deletion cascade.

It seams that generic.GenericForeignKey() cannot be set to allow NULL values. Is there a way to do this, or if not how can a standard CharField holding a UUID primary key and a sperate CharField holding the model name be used in a similar fashion?

like image 637
Marcus Whybrow Avatar asked Mar 01 '10 16:03

Marcus Whybrow


People also ask

What is a Generic foreign key?

In Django, a GenericForeignKey is a feature that allows a model to be related to any other model in the system, as opposed to a ForeignKey which is related to a specific one.

What is generic relation in Django?

Basically it's a built in app that keeps track of models from the installed apps of your Django application. And one of the use cases of the ContentTypes is to create generic relationships between models.


1 Answers

For the lazy/pragmatic:

class MyModel(models.Model):     ...other fields...     content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL)     object_id = models.PositiveIntegerField(blank=True, null=True)     content_object = generic.GenericForeignKey('content_type', 'object_id') 
like image 193
Mark Chackerian Avatar answered Sep 22 '22 18:09

Mark Chackerian