ForeignKey field problem in Django
I have declared two of my models this way:
class EmailAddress(models.Model):
customer = models.ForeignKey(Customer)
email_address = models.CharField(max_length=200)
def __unicode__(self):
return self.email_address
class Customer(models.Model):
.
.
.
email_address = models.ForeignKey(EmailAddress)
def __unicode__(self):
name = ''+str(self.title)+" "+str(self.first_name)+" "+str(self.last_name)
return name
The idea is that one customer can have several email addresses associated to him/her...the problem is how to do this correctly...as you can see from my code above, the customer foreign key field has to be after the customer class, but the email address foreign key field has to be after the EmailAddress class...how do I sort out this iss开发者_Python百科ue?
There is a serious logic flaw here - ForeignKey
from Customer
to Email
would mean that each customer has only one email. You would want to skip that foreignkey alltogether:
class Email(models.Model):
customer = models.ForeignKey(Customer, related_name='email_addresses')
then simply do customer.email_addresses
to get a list of all emails. You dont need another ForeignKey
, django uses relationships defined in one model (unlike RoR and other MVC frameworks)
I don't see why you want to use a ForeignKey in EmailAddress.
Extract from Python web development with Django:
Foreign keys are generally used to define one-to-many (or many-to-one) relationships. In the next example a Book has a single Author and an Author can have many Books.
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)
Just add single-quotes around Customer:
class EmailAddress(models.Model):
customer = models.ForeignKey('Customer')
email_address = models.CharField(max_length=200)
def __unicode__(self):
return self.email_address
Menda's answer is correct. There isn't really an ordering problem because the Customer model doesn't need a ForeignKey field. Just remove that and flip the order in which the classes are defined.
class Customer(models.Model):
pass
class EmailAddress(models.Model):
customer = models.ForeignKey(Customer)
email_address = models.CharField(max_length=200)
There's also a Django email field you can use. See Django EmailField. Just wanted to mention that in case it could add value to you application.
精彩评论