django using columns from other models without inheritance
am not entirely sure if what am about to do is programmically possible. Although if this works, It will help me a lot organize my code.
class AuditColumns(models.Model):
created_at=models.DateField("Created at")
created_by=models.开发者_如何学CForeignKey(User, db_column="created_by", related_name="%(app_label)s_%(class)s_y+")
updated_at=models.DateTimeField("Updated at")
updated_by=models.ForeignKey(User, db_column="updated_by", null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
class Meta:
abstract = True
def return_audit_columns(self):
return self.created_at, self.created_by, self.updated_at, self.updated_by
class Choice(models.Model):
choice=models.CharField(max_length=200)
def __init__(self):
self.created_at, self.created_by, self.updated_at, self.updated_by=AuditColumns.return_audit_columns(self)
the code above does not work, it was my attempt or what I wish to do. Basically, I have the class AuditColumns which contain this set of columns and I wish to use them in different models across my projects. I do not want the Choice model to inherit from AuditColumns because am going to use the same technique to include other columns from other sources into my Choice class.
off course what I wrote above is not practical either because I will have to repeat the column names every time I want to include the AuditColumns in one of the models across my project.
Is what I want to do achievable or not?
The usual way to do this is with content types. You create a model similar to AuditColumns
, but you also include another field, a GenericForeignKey
, which can point to any model within the project's database.
Python will let you do multiple inheritance so you can inherit the attributes of multiple base classes into your Choice class, that may be what you want.
class Choice(AuditColumns,Foo):
choice=models.CharField(max_length=200)
Would give your Choice class the attributes of the AuditColumns class, and the Foo class. You are also misusing self in your example. You are calling the return_audit_columns method of the AuditColumns class that is expecting an instance of that class but passing in an instance of the Choice class which is not what you want.
精彩评论