简体   繁体   中英

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.

We can call .questions.add() on the saved object with *questions as argument to do that.

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.

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(*objs)
Adds the specified model objects to the related object set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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