Skip to content

Instantly share code, notes, and snippets.

@cyface
Created July 21, 2012 22:29
Show Gist options
  • Save cyface/3157428 to your computer and use it in GitHub Desktop.
Save cyface/3157428 to your computer and use it in GitHub Desktop.
Django Many-To-Many Create With Intermediary (Through) Table
"""Django M2M With Through Example Models"""
import datetime
from django.db import models
class Child(models.Model):
"""Each Child can have multiple families."""
name = models.CharField(max_length=120)
families = models.ManyToManyField('Parent', through='FamilyChild')
class Family(models.Model):
"""Families are groups of children in a particular order."""
name = models.CharField(max_length=255)
children = models.ManyToManyField('Child', through='FamilyChild')
class FamilyChild(models.Model):
"""A FamilyChild is the many-to-many intersection of Families and Children"""
child = models.ForeignKey('Child', related_name='children')
family = models.ForeignKey('Family', related_name='families')
order = models.IntegerField(default=0)
@vkgitrep
Copy link

vkgitrep commented Dec 7, 2015

am getting a Noreversematch for the url {% url child_create slug=form.family_slug.value %}"

basically i have this child_create under an app

main urls.py
url(r'^samrunbook/', include('samrunbook.urls')),

samrunbook/urls.py

url(r'sam/(?P<slug>[0-9]+)/add/account/$', views.AccountAdd.as_view(), name='account_create'),

So, if I understand correctly, account_create will be e.g sam/8/add/account, but it won't be resolved unless the urls start with

samrunbook/sam/8/add/account

Can you please help how to resolve this issue?.

@shravan-infrrd
Copy link

shravan-infrrd commented Jul 11, 2018

Hi, I would like to know how are you using the order filed in the through table(FamilyChild).

My question and curiosity is how do we get the list of child in the order mentioned in the FamilyChild model. It would help me understand the extra filed in the model, am new to Django. Expecting something like this.
child1 = Child.create(name='first_child')
child2 = Child.create(name='second_child')
family = Family.create(name='sample_family_name')
family.children.create(child=child1, order=1)
family.children.create(child=child2, order=2)

Now?
family.childrens.order_by(:order) ===> something like. How do we do ? Am from rails background new to django.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment