Django ForeignKey汽车领域

时间:2013-11-11 14:23:58

标签: python django

我有User型号:

class User(models.Model):
    SEX = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    name = models.CharField("Name", max_length=100, blank=False)
    surname = models.CharField("Surname",max_length=150, blank=False)
    is_real = models.BooleanField("Real user", default=False)
    sex = models.CharField("Sex", max_length=1, choices=SEX)
    age = models.IntegerField("Age", blank=False)

每个User都有一封电子邮件或一些:

class Email(models.Model):
    address = models.EmailField("Email Address", max_length=250)
    login = models.CharField("Login", max_length=50)
    password = models.CharField("Password", max_length=15)
    date_created = models.DateField("Registered", auto_now_add=True)
    last_login = models.DateTimeField("Last login")
    belongs_to = models.ForeignKey(User, verbose_name="Owner")

User也可能有博客:

class Blog(models.Model):
    address = models.URLField("Blog Url")
    related_email = models.ForeignKey(Email, verbose_name="Registered with")
    belongs_to = models.ForeignKey(User, blank=True)

博客通常在电子邮件中注册。所以我需要的是,如果我没有指定博客的所有者,它应该自动设置为注册电子邮件的所有者。我认为可以通过覆盖save方法来完成,但不能确定如何处理ForeignKey关系。

2 个答案:

答案 0 :(得分:2)

你不能做这样的事吗?

def save(self, *args, **kwargs):
    if not self.belongs_to:
        self.belongs_to = self.related_email.belongs_to
    return super(Blog, self).save(*args, **kwargs)

答案 1 :(得分:0)

首先,将null = True添加到Blog.belongs_to

假设您知道注册电子邮件的所有者,则可以

owner = User.objects.get(field = value)
email = Email.objects.get(belongs_to = owner)
Blog.objects.create(address = ..., related_email = email, belongs_to = None)

然后你需要做任何更新,你可以做

blog = Blog.objects.filter(related_email = email).filter(belongs_to__isnull = True)
blog.belongs_to = newUserObject