bumbo
bumbo

Reputation: 1

Model design question: custom fields at runtime?

I have some newbie questions about Django.

I want to write a generic ticket-management system, where the administrator of the site should be able to add custom fields to a ticket. It seems that the database tables are generated on initialization, so it is not clear to me how to add custom fields at runtime. One way is to have a long list of fields of different types, all nullable, and let the administrator rename/select the fields she needs. Is there a better design?

Thanks!

Upvotes: 0

Views: 303

Answers (2)

Jack Ha
Jack Ha

Reputation: 20961

I would make something like the code below. Store extra attributes in an attribute model. Store the values in AttributeValue.

class Ticket(models.Model):
    name = models.CharField(max_length=200)


class Attribute(models.Model):
    name = models.CharField(max_length=200)


class AttributeValues(models.Model):
    attribute = models.ForeignKey(Attribute)
    ticket = models.ForeignKey(Ticket)
    value = models.CharField(max_length=200)

Upvotes: 0

Josiah
Josiah

Reputation: 4854

I'm currently in charge of maintaining a similar site where a treatment for a medical condition is listed and there can be arbitrary number of "cases" which are user-posted experiences for that treatment/condition combo attached.

The method my company used to set it up was to have an Entry object which would be analogous to the custom field you described, which has a Foreign Key referencing the treatment/condition to which it belongs.

Then when we want to get all the entries for a particular treatment/condition combo, we simply do an

Entry.objects.filter(condition=ID)

So, in your case, I would suggest having a Ticket model, and an "Entry" style model which contains a Foreign Key reference to the Ticket to which it belongs.

Upvotes: 1

Related Questions