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?
-
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 -
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) -
There is a serious logic flaw here -
ForeignKeyfromCustomertoEmailwould 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_addressesto get a list of all emails. You dont need anotherForeignKey, django uses relationships defined in one model (unlike RoR and other MVC frameworks)
0 comments:
Post a Comment