Ace_Gentile
Ace_Gentile

Reputation: 244

Django models: form with infinite group of fields repetition

I'm studying django these days and I need your help to find a solution to this problem about form construction.

Let's say I have an entity called 'Activity' just made up by:

- title: just a char field
- ActivityYears: a couple of start-end years that can be repeated multiple times

ActivityYears is made up by:

- start year
- end year 

That's how my database should look like:

activity_table
-ID
-title

activity_years_table
-year start
-year end
-activity ID

That's how it looks like front-end

Activity title 1
2001 - 2003
2005 - 2006
2007 - 2010

Activity title 2
2011 - 2013
2015 - 2016

and so on

I'd dare to say that Activity and ActivityYears are models but I cannot connect them in a proper way. When I add an Activity item I should be able to add as many start-end years as I need but how?

Thanx in advance

Upvotes: 0

Views: 478

Answers (1)

Michael Fourre
Michael Fourre

Reputation: 3015

You'll likely want to use two separate models with a Foreign Key relationship. For example:

class Activity(Model):
    id = AutoField(editable=False, primary_key=True, unique=True)
    title = CharField(default="Activity")

class ActivityYear(Model):
    id = AutoField(editable=False, primary_key=True, unique=True)
    year_start = IntegerField(default=1900)
    year_end = IntegerField(default=1999)

    activity_id = ForeignKey(Activity)

With this model design, we can define that each ActivityYear had a member activity_id which points to the id field of a valid Activity row in the database. With this information, you would be able to select ActivityYear objects from the database using the respective Activity object's id member:

SELECT * FROM activity_years WHERE activity_id = 1

or in Django:

activity_years = Activity.objects.filter(activity_id=1)

In order to add ActivityYear objects which map to a specific Activity object, you can use the following:

ActivityYear.objects.create({
    'year_start': 1990,
    'year_end': 1999,
    'activity_id': 1,
})

Let me know if this answers your question.

Upvotes: 4

Related Questions