Django models: form with infinite group of fields repetition
<p>I'm studying django these days and I need your help to find a solution to this problem about form construction.</p>

<p>Let's say I have an entity called 'Activity' just made up by:</p>

<pre><code>- title: just a char field
- ActivityYears: a couple of start-end years that can be repeated multiple times
</code></pre>

<p>ActivityYears is made up by:</p>

<pre><code>- start year
- end year 
</code></pre>

<p>That's how my database should look like:</p>

<pre><code>activity_table
-ID
-title

activity_years_table
-year start
-year end
-activity ID
</code></pre>

<p>That's how it looks like front-end</p>

<pre><code>Activity title 1
2001 - 2003
2005 - 2006
2007 - 2010

Activity title 2
2011 - 2013
2015 - 2016

and so on
</code></pre>

<p>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?</p>

<p>Thanx in advance</p>

<p>You'll likely want to use two separate models with a <code>Foreign Key</code> relationship. For example:</p>

<pre><code>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)
</code></pre>

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

<p><code>SELECT * FROM activity_years WHERE activity_id = 1</code></p>

<p>or in Django:</p>

<p><code>activity_years = Activity.objects.filter(activity_id=1)</code></p>

<p>In order to add <code>ActivityYear</code> objects which map to a specific <code>Activity</code> object, you can use the following:</p>

<pre><code>ActivityYear.objects.create({
    'year_start': 1990,
    'year_end': 1999,
    'activity_id': 1,
})
</code></pre>

<p>Let me know if this answers your question.</p>

python django