silviud
silviud

Reputation: 1025

Django dynamic embedded/nested models

I have an application that knows about a type of an entity at creation time. Because of this I don't know how to properly link the associated models however I see it like

The e_type field is a simple CharField, based on what value it has, I query Type_a or Type_b.

This is how it looks now into django

class Entity(models.Model):
   name = models.CharField(max_lenght=64)
   e_type = models.CharField(max_lenght=1)

class Type_a(models.Model):
   entity = models.OneToOneField(Entity)
   attribute = models.CharField(max_lenght=64)

class Type_b(models.Model):
   entity = models.OneToOneField(Entity)
   attribute = models.CharField(max_lenght=64)

What would you suggest ?

thanks

Edit: In response of why are multiple tables - each e_type referees to a different table structure. For example type_a has four fields, type_b has ten fields and so on. Having a json field is simple since it can store any data so no need to have multiple tables each with it's own structure. A different option I can see is to use something like EAV.

Upvotes: 2

Views: 272

Answers (2)

Basti
Basti

Reputation: 252

I'm not sure I understand the question, but why do you want to have three different tables? I would recommend something like this:

#in models.py
class Entity(models.Model):
    TYPE_CHOICES = (('A', 'Type A'),
                ('B', 'Type B'))
    name = models.CharField(max_length=64)
    type = models.CharField(max_length=1, Choices=TYPE_CHOICES)
    attribute = models.CharField(max_length=64)

This has the following advantages:

  • If you use model forms, they will be automatically generated with your choices as options
  • If you need a new choice in the future, because you have a new entity, all you have to do is add a new entity to the TYPE_CHOICES tuple
  • Making queries is easy. If you want to find all of your entities that are Type A, your query is simply: Entity.objects.all().filter(type__eq='A')

Upvotes: 0

Joseph Paetz
Joseph Paetz

Reputation: 876

I am not sure if I am interpreting your question correctly, but perhaps, using inheritance, something like this...

class Entity(models.Model):
    name = models.CharField(max_length=64)
    # Other parent attributes.

class EntityA(Entity):
    # unique attributes.

class EntityB(Entity):
    # unique attributes.

Upvotes: 1

Related Questions