Search code examples
sqldjangosqlitemodelmanytomanyfield

Django: ManyToManyField with additional Column


I am trying to create a job application-form with Django.

Basically, I created two models.

  • softwareskill_model
  • application_model

The admin can log into the admin-section and add new softwareskill- entries to the database. The application_model references those softwareskill-entries/records using a ManyToMany-Field:

class softwareskill_model(django.db.models.Model):
    name = django.db.models.CharField(max_length=200)

class application_model(django.db.models.Model):
    # ...
    softwareskills = django.db.models.ManyToManyField(softwareskill_model)

So if someone wants to apply for the job, he can select which software-packages he uses.

Now I want the applicant to make a rating from 1-6 for each software-skill he has selected. How do you do that?

I am using a SQLite3 database and discovered that the ManyToManyField creates a new table to store the relationship. In my case it looks like this:

| ID | application_model_id | softwareskill_model_id |

My assumption would be to simply add a new column so it looks like this:

| ID | application_model_id | softwareskill_model_id | Rating |

Is that possible / the best way to do it? How?

I am very new to Django, databases and web-development in general and hope you can help me :-)!

Thank you, Henry


Solution

  • through is what you need to use, e.g.

    class softwareskill_model(django.db.models.Model):
        name = django.db.models.CharField(max_length=200)
    
    class application_model(django.db.models.Model):
        # ...
        softwareskills = django.db.models.ManyToManyField(softwareskill_model, through="ApplicationSoftwareSkill")
    
    class ApplicationSoftwareSkill(models.Model):
        softwareskill = models.ForeignKey(softwareskill_model)
        application = models.ForeignKey(application_model)
        # extra fields here e.g.
        rating = models.IntegerField()