Skip to content Skip to sidebar Skip to footer

When Creating A Model Instance How To Fill Manytomany Field?

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_ob

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

Post a Comment for "When Creating A Model Instance How To Fill Manytomany Field?"