I need to add extra columns if product is in a particular category. I thought of using JSON
or allowing null columns, but is there any better way of handling this situation. I’m using Postgresql database. Here are my model structure.
class Product(Base):
def __str__(self):
return self.name
name = models.CharField(max_length=255, unique=True, validators=[validate_alphanumeric])
is_safari = models.BooleanField(default=True)
Product table has mapped to agents like this
class Agent(Base):
def __str__(self):
return self.agent_user.username
agent_user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.RESTRICT,
)
country = CountryField()
city = models.CharField(max_length=255)
AgentProduct
model
class AgentProduct(Base):
agent = models.ForeignKey(
Agent,
on_delete=models.RESTRICT,
)
product = models.ForeignKey(
Product,
on_delete=models.RESTRICT,
)
a_rate = models.IntegerField()
c_rate = models.IntegerField()
I would like to add some extra information if is_safari
is true to the AgentProduct
model like
per_v_charge = models.IntegerField()
extra_p_charge = models.IntegerField()
# something like this
2
Answers
You can use mongoDb for schemaless database structure. You can create different "columns" for different "rows" with it.
Two categories for making the desition come in form what is best for you and for the app:
Evaluating what is best for you is to define what is easy to read and understand to other developers; usually, the solution with less code and easier to document is likely better all the time.
To evaluate what is best for the app is to define what is heavy for Django or postgres to handle, nowadays postgres handles very well JSON fields and Django supports them as if they were important for the ORM. Still, once again, you have to throw consistent schemas for it to be efficient.