问题
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 retweet
objects.
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