如何填充ManyToMany字段

如何填充ManyToMany字段

本文介绍了创建模型实例时,如何填充ManyToMany字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建这样的模型实例:

I want to create model instance like this:

new_tweet = Tweet.objects.create(text = tweet_object.text, date = tweet_object.date, username = tweet_object.username, retweet = tweet_object.retweet.all(), is_ret = True)

一切顺利,直到: retweet = tweet_object.retweet.all()。它将返回此错误: retweet是此函数的无效关键字参数

It's all going well until this: retweet = tweet_object.retweet.all(). It returns this error: 'retweet' is an invalid keyword argument for this function

这是ManyToMany字段。那么在创建新的模型实例时如何填充此字段?

This is a ManyToMany field. So how to fill this field when creating new model instance?

通过 tweet_object.retweet.all()由许多转推对象组成。

编辑:

Model:

class Tweet(models.Model):
    text = models.CharField(max_length=140)
    date = models.DateTimeField(auto_now_add=True)
    username = models.CharField(max_length=140)
    favourite = models.ManyToManyField(Favourite)
    retweet = models.ManyToManyField(Retweet)
    replies = models.ManyToManyField('Tweet')
    is_ret = models.BooleanField(default=False)

    def __unicode__(self):
        return self.username

还有tweet_object,这只是另一条推文:

And tweet_object, which is just another tweet:

tweet_object = Tweet.objects.get(id=tweet_id)


推荐答案

我认为您应该首先创建Tweet对象,然后再创建与转推建立关系。

I think you should create Tweet object first and next you can create relations with retweets.

有关可在此处找到的信息的更多信息:

More about information you can find here: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

简单地:

tweet_object = Tweet.objects.get(id=tweet_id)

new_tweet = Tweet.objects.create(text = tweet_object.text, date = tweet_object.date, username = tweet_object.username, is_ret = True)

for retweet in tweet_object.retweet.all():
    new_tweet.retweet.add(retweet)

new_tweet.save()

这篇关于创建模型实例时,如何填充ManyToMany字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:56