Django Inheriting Multiple Tables: Provide an Individual Single Column Name

I am trying to create a Django ORM mapping compatible with an existing data model , so I am trying to work with an existing set of table and column names.

I have an inheritance situation with multiple tables where the InformationObject class comes from the Object class. I would like Django to handle this in the usual way:

class Object(models.Model): class Meta: db_table = "object" class InformationObject(Object): class Meta: db_table = "information_object" 

In this case, Django will automatically create a one-to-one field in the inheriting model named object_ptr_id . However, in the scheme I am forced to use, the object reference is simply called "id". So:

Is there any way to specify the name of a Django column automatically used for multi-valued inheritance?

An alternative that I should use otherwise is to use an explicit one-to-one field, but then I will not be able to inherit methods other than the database from the object model:

 class Object(models.Model): class Meta: db_table = "object" class InformationObject(models.Model): class Meta: db_table = "information_object" id = models.OneToOneField(Object, primary_key=True, db_column="id") 

Any ideas? Perhaps I could create a common base class for both of them and put non-db methods there ...?

+6
source share
2 answers

From django docs (development version):

As already mentioned, Django will automatically create OneToOneField, linking your child class with any non-abstract parent models. If you want to control the attribute name associated with the parent, you can create your own OneToOneField and set parent_link = True to indicate that your field is a reference to the parent class.

+8
source

As mentioned in the @fusion app from the docs, you need to create OneToOneField if you want to specify a column when using model inheritance. Inherited fields will be available in the child class both in the self field and in the one-to-one field.

 class Object(models.Model): class Meta: db_table = "object" column_1 = models.CharField() class InformationObject(Object): class Meta: db_table = "information_object" # arbitrary property name (parent_link) parent_link = models.OneToOneField(Object, primary_key=True, db_column="id", parent_link=True) 

In this example:

 >>> inf_obj = InformationObject.objects.get(pk=1) >>> print inf_obj.column_1 == inf_obj.parent_link.column_1 True 
+1
source

Source: https://habr.com/ru/post/896399/


All Articles