Django中的ForeignKey字段问题 [英] ForeignKey field problem in Django

查看:143
本文介绍了Django中的ForeignKey字段问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式声明了两个模型:

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

这个想法是,一个客户可以拥有与他/她关联的几个电子邮件地址...问题是如何正确执行此操作...从上面的代码中可以看到,客户外键字段必须位于客户类别之后,但是电子邮件地址外键字段必须位于EmailAddress类之后...如何解决此问题?

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?

推荐答案

我不明白为什么您要在EmailAddress中使用ForeignKey。

使用Django的Python网络开发中提取

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)

这篇关于Django中的ForeignKey字段问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆