Reputation: 412
I am trying to use some common attributes for all my objects in the DB like created_by, updated_by, created_when and updated_when.
So I created a class for the common attributes:
class CommonModel(models.Model):
"""Common fields that are shared among all models."""
created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,
editable=False, related_name="+")
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,
editable=False, related_name="+")
created_at = models.DateTimeField(auto_now_add=True,
editable=False)
updated_at = models.DateTimeField(auto_now=True,
editable=False)
Then I refer to the common model in my models:
class Tag(CommonModel):
"""Tag to be used for products"""
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Vendor(CommonModel):
"""Vendor to be used for products"""
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
But when I refer to the tag or vendors in another model as foreign_key then I get an error while executing the migration.
class Product(CommonModel):
"""Model for the type of a product"""
product_id = models.CharField(max_length=255, unique=False)
description = models.CharField(max_length=255, unique=False, null=True, blank=True, default='')
vendor = models.ForeignKey(Vendor, blank=False, null=False, on_delete=models.SET_DEFAULT)
tag = models.ForeignKey(Tag, null=True, blank=True, on_delete=models.SET_NULL)
Error message:
SystemCheckError: System check identified some issues:
ERRORS:
core.Product.tag: (models.E006) The field 'tag' clashes with the field 'tag' from >model 'core.commonmodel'.
core.Product.vendor: (models.E006) The field 'vendor' clashes with the field 'vendor' from model 'core.commonmodel'.
It was working fine before I introduced the common models.
Upvotes: 1
Views: 60
Reputation: 811
You need to set abstract in Meta, after that it should work fine.
class CommonModel(models.Model):
"""Common fields that are shared among all models."""
created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,
editable=False, related_name="+")
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,
editable=False, related_name="+")
created_at = models.DateTimeField(auto_now_add=True,
editable=False)
updated_at = models.DateTimeField(auto_now=True,
editable=False)
class Meta:
abstract = True
Upvotes: 2