When creating a model instance how to fill ManyToMany field?

喜夏-厌秋 提交于 2019-12-12 04:53:46

问题


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)

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

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

By the way tweet_object.retweet.all() is consisted of many retweetobjects.

EDIT:

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

And tweet_object, which is just another tweet:

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

回答1:


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/

It's very simply:

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()


来源:https://stackoverflow.com/questions/26672337/when-creating-a-model-instance-how-to-fill-manytomany-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!