Django many-to-many relationship with optional fields

I am creating a simple interface for a biological database using django-admin to populate db. I want tot to use the many-to-many relationship for the fish species questionnaire (one questionnaire can have more than one species, and one species can be present in more than one questionnaire). Two models in question:

class Species(models.Model): fish_spp_name = models.CharField(max_length=255, unique=True) class Questionaire(models.Model): # ... fish_caught = models.ManyToManyField(Species) 

Now, I want my data to contain the amount of each species caught on the questionnaire. So, for example, I can associate 3 different species with the id = 1 questionnaire, but how to include this, say, 2 from the first species, 1 from the second and 4 of the third were caught?

+4
source share
2 answers

Define other Caught models to hold information for each capture. Give it a related_name to make it easy to access your code. You may also want unique_together matching fields.

 class Species(models.Model): name = models.CharField(max_length=255, unique=True) def __unicode__(self): return '%s/%d' % self.name class Questionaire(models.Model): pass class Caught(models.Model): species = models.ForeignKey(Species) number = models.IntegerField() questionaire = models.ForeignKey( Questionaire, related_name='catches') def __unicode__(self): return '%s/%d' % (self.species.name, self.number) 

Use it as follows:

 (InteractiveConsole) >>> from app.models import * >>> s1 = Species(name='Salmon') >>> s1.save() >>> s2 = Species(name='Mackerel') >>> s2.save() >>> q = Questionaire() >>> q.save() >>> c1 = Caught(species=s1, number=7, questionaire=q) >>> c2 = Caught(species=s2, number=5, questionaire=q) >>> c1.save() >>> c2.save() >>> q.catches.all() [<Caught: Salmon/7>, <Caught: Mackerel/5>] >>> 
-3
source

All Articles