Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Foreign Key to Many to Many Table

I need help in setting up my models correctly. Say I have three models:

  • Account
  • Owner
  • Transaction

Account and Owners are many to many, so:

class Account(models.Model):
    number = models.CharField(max_length=10)

class Owner(models.Model):
    account = models.ManyToManyField(Account)
    fullName = models.TextField()

Then, an "AccountOwner" can make many transactions. So, if my wife and I have the same account, I can make a many transactions for t, and she can.

My first attempt at a transaction model:

class Transaction(models.Model):
    #Does not work - Could pick account owner is not on
    account = models.ForeignKey(Account)
    owner = models.ForeignKey(Owner)
    title = models.CharField('title', max_length=50)

Two foreign keys do not work. I need one foreign key on the account_owner table. Can I do this without creating an actual account_owner model?

Thank you for your time

like image 789
Ryan Tankersley Avatar asked Jan 18 '15 05:01

Ryan Tankersley


1 Answers

In fact you had already created account_owner model. It is invisible in code but it is exists. You can make it visible and use through argument in M2M field:

class Owner(models.Model):
    accounts = models.ManyToManyField(Account, through='OwnerAccount')
    fullName = models.TextField()

class OwnerAccount(models.Model):
    owner = models.ForeignKey(Owner)
    account = models.ForeignKey(Account)

class Transaction(models.Model):
    owner_account = models.ForeignKey(OwnerAccount)
    title = models.CharField('title', max_length=50)

You can still access to your Owner.accounts many-2-many field as usual. So then you will call owner.acounts.add(some_account) the corresponding OwnerAccount instance will be created automatically.

like image 166
catavaran Avatar answered Sep 20 '22 18:09

catavaran