简体   繁体   English

与Django中另一个模型的查询集创建多对多关系

[英]Create many to many relation with query set of another model in Django

So I have an email model which will contain loads of questions. 因此,我有一个包含大量问题的电子邮件模型。 For now, I want the email model to automatically add all of the questions when it saves the model. 现在,我希望电子邮件模型在保存模型时自动添加所有问题。

So far, this is what my question and email models look like: 到目前为止,这是我的问题和电​​子邮件模型的样子:

class Email(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100)
    slug = models.SlugField()
    jobnumber = models.IntegerField()
    developer = models.ForeignKey(User, related_name="developer")
    questions = models.ManyToManyField('Question', related_name="questions")
    checked_questions = models.ManyToManyField('Question', related_name="checked_questions")
    signed_off = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        self.questions = Question.objects.all()
        super(Email, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('checklists:detail', args=[str(self.slug)])

class Question(models.Model):
    title = models.CharField(max_length=100)

    def __unicode__(self):
        return self.title

I thought that this would just work self.questions = Question.objects.all() but it didn't so any help would be great. 我认为这只会对self.questions = Question.objects.all()起作用,但事实并非如此,因此任何帮助都将是很大的。

We can call .questions.add() on the saved object with *questions as argument to do that. 我们可以使用*questions作为参数在保存的对象上调用.questions.add()

First we will save the object in the db. 首先,我们将对象保存在数据库中。 Then, we pass the the questions objects using * option to associate all the questions with the email object. 然后,我们使用*选项传递questions对象,以将所有questionsemail对象相关联。

You can do the following: 您可以执行以下操作:

class Email(models.Model):

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)        
        super(Email, self).save(*args, **kwargs) # save the object first
        question_objs = Question.objects.all() 
        self.questions.add(*question_objs) # add all questions using * 

From the docs on .add() : .add()上的文档中

add(*objs) 加(* OBJ文件)
Adds the specified model objects to the related object set. 将指定的模型对象添加到相关的对象集中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM