When creating a model instance how to fill ManyToM

2019-09-04 22:23发布

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条回答
Juvenile、少年°
2楼-- · 2019-09-04 23:20

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()
查看更多
登录 后发表回答