0

我有一个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关系。

4

2 回答 2

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)
于 2013-11-11T14:35:14.620 回答
-1

首先,添加null = TrueBlog.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
于 2013-11-11T14:35:46.907 回答