I am confused as far as Database design goes for a Django application with specific relationships. I have been looking at the following database schema : http://www.databaseanswers.org/data%5Fmodels/customers_and_orders/index.htm
I am confused about the relationships between Customer_addresses and Customers, and Addresses.
I know that:
Does this equate to a many to many relationship?
When I'm building the model in django I have (simplified):
class Customer_Address(models.Model):
customer = models.ManyToManyField('inventory.Customer')
address = models.ManyToManyField('inventory.Address')
Is this right? or does this make more sense:
class Customer_Address(models.Model):
customer = models.ForeignKeyField('inventory.Customer')
address = models.ManyToManyField('inventory.Address')
UPDATED QUESTION:
Based on the idea that it is a many to many relationship. Does one ManyToMany relation, require two ManyToManyFields?
Based on the following: http://en.wikipedia.org/wiki/Many-to-many_%28data_model%29
Since Django supports ManyToManyFields, do I not even require the junction table? And if I do use the junction table (Customer_addresses) the article seems to imply using Two OneToMany relationships, which wouldn't that just be two foreign keys like this?
class Customer_Address(models.Model):
customer = models.ForeignKeyField('inventory.Customer')
address = models.ForgeinKeyField('inventory.Address')
UPDATED QUESTION:
Now that we know that Django builds the intermediate table, and the table Customer_Addresses is not required. Which table should have the ManyToManyfield? the customer tables? or the Address table?
Example: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
In the Person/Groups examples.. The Groups has the ManyToManyField. Is there any reason the ManyToManyfield couldn't be defined in the Person table?
For the first question.
When a relationship states that
one customer can have Many addresses.
many customers can have the same (one) address
Than its clearly a Many-to-Many relationship and always use ManyToManyField
Now for the second question.
What if you want to have a intermediate table which has extra fields between two many to many entities(Tables/models)
Than create a new Model which has a ForiegnKey from the other two models. As in
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __unicode__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
For more Read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With