I'm new to django.
In my project, I have so far an app with a student model. Model's fields are name grades (ie math, english....) and comments. This is working just fine.
Now I need to add after school activities (ie football, dance, guitar....)
The problem starts here, I need to do a model for the activity which acts like a python dict, activity is the dict, student is the key and hours spend in the activity are the values.
It is typically a M2M relation: an activity has several students, and a student can be in several activities with a different amount of participation in each one.
On stackoverflow I've found this answer: How to store a dictionary on a Django Model? witch is really close but not there yet.
I tried different options. Right now I have this:
In studentapp.models:
class Student(models.Model):
nom = models.CharField(max_length=50, blank=True)
#grades are all integer fields
commentaires = models.TextField(max_length=250, blank=True)
class Edudient(models.Model): #frensh for student BTW
nom = models.OneToOneField(Etudient, db_index=True, on_delete=True)
hours = models.IntegerField(default=0)
in activity.models:
class Activity(models.Model):
nom = models.CharField(max_length=50, help_text="exemple: 'Activity football'")
def __str__(self):
return self.nom
class WhoIsActive(models.Model):
activity = models.ForeignKey(Activity, db_index=True, on_delete=True)
who = models.ForeignKey(Etudient, db_index=True, on_delete=True)
def __str__(self):
return str(self.activity) if self.activity else None
With this I can:
- create as many
Etudient
instances as I want all with a separate number of hours - After creating them, I can add them to the
WhoIsActive
- Create an activity from
WhoIsActive
I can not:
- Create
Etudient
directly fromWhoIsActive
Etudient
's instances areStudent
's query, not instances
I feel like I am pretty close, but I don't know what I am doing wrong. Any ideas?
Thank you for future answers.