skip to Main Content

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


  1. You can use mongoDb for schemaless database structure. You can create different "columns" for different "rows" with it.

    Login or Signup to reply.
    1. Add nullable fields first.
    2. Wait for A. need to add more and more nullable columns and B. building more and more queries using these nullable fields.
    3. Based on gathered evidence of data and use cases, evaluate what is best, whether keeping them as nullable columns or adding a JSON field.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search