views:

154

answers:

3

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 issue?

+2  A: 

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
Matthew Christensen
+2  A: 

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)
Menda
+4  A: 

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)

kibitzer