Reputation: 2254
I am migrating my app to Django and using their built-in ORM instead of writing SQL queries. The problem I am having is with one of my many to many relationships. I have the following models:
class Orgs(models.Model):
org = models.AutoField(primary_key=True)
org_name = models.CharField(max_length=45, null=False)
org_hood = models.CharField(max_length=60, null=False)
creation_date = models.DateField(auto_now_add=True)
class Members(models.Model):
member_ID = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
nick_name = models.CharField(max_length=20, null=False)
is_self_managed = models.BooleanField(default=True)
orgs = models.ManyToManyField(Orgs, null=True)
There are many Orgs and many Members. A member can be part of many Orgs and an Org can have many members. Each member has a balance ($0.00) associated to the Org they are a part of. For example:
member1 is in Org1 with a balance of $3.85
member1 is in Org2 with a balance of $2.00
member2 is in Org1 with a balance of $0.85
I can't figure out how to define this balance field. When I wasn't using the ORM, I manually created the join table and defined these fields I needed right in the join table.
Upvotes: 1
Views: 1778
Reputation: 48952
Using the through
argument to ManyToManyField
you can explicitly define the join table and put the balance field there.
class Orgs(models.Model):
...
members = ManyToManyField(Members, through='Membership')
class Members(models.Model):
...
class Membership(models.Model)
org = models.ForeignKey(Orgs)
member = models.ForeignKey(Members)
balance = models.DecimalField() # or whatever your field type is
Upvotes: 7