Create base Django model class for DB-view related models setting all ForeignKey-fields to on_delete=DO_NOTHING -


in django (1.6+) application, have many django models point (read only) db views. these models contain foreign key relations. if django application tries delete related fk-models, lead db errors ("cannot delete view") if don't set cascade=do_nothing on all foreign key fields.

example:

class personview(models.model):     person = models.foreignkey(person, db_column='fk_person', on_delete=do_nothing)      class meta:         db_table = 'view_persons'         managed = false 

since db-view-model-foreignkey-fields should have cascade=do_nothing default, i'd create db-view model base class automatically set foreign-key-fields on_delete=do_nothing, need care inheriting model - otherwise it's easy forget (and redundant) setting attribute fields. in end want end code this:

class viewmodel(models.model):     class meta:         abstract = true      def __init__(self, *args, **kwargs):         super(viewmodel, self).__init__(*args, **kwargs)         # how set foreign-key fields' on_delete attribute "do_nothing"?   class personview(viewmodel):     # no need set on_delete anymore     person = models.foreignkey(person, db_column='fk_person')      class meta:         db_table = 'view_persons'         managed = false 

how can alter django model attributes in base class set foreign key fields on_delete=do_nothing?

well, can monkey-patch models.foreignkey more preferred method subclass foreignkey:

class myforeignkey(models.foreignkey):     def __init__(self, *args, **kwargs):         super(myforeignkey, self).__init__(*args, **kwargs)         self.on_delete = models.do_nothing 

then can use myforeignkey instead of foreignkey in models.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -