2

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

  • have the type embedded into a json field as an attribute for Entity
  • have some relation between 'fixed' tables (see bellow)

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.

1
  • In the end I went with having a json field. I loose the built in validation however I can have a different way to validate the data. Commented Aug 26, 2013 at 12:16

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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')

1 Comment

If each type of entity has unique attributes, then I would recommend Joseph's answer above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.