我有这个模型类:
class Article(models.Model):
[many fields]
class ArticleArchive(models.Model):
[same fields as Artilce model]
我希望从Article表中获取对象并将其移动到ArticleArchive表:
articles = Article.objects.filter(date__year=2011)
for art in articles:
[and there moving objects]
怎么做?
答案 0 :(得分:10)
articles = Article.objects.filter(date__year=2011).values()
for art in articles:
ArticleArchive.objects.create(**art)
答案 1 :(得分:6)
为了获得更好的性能,最好使用ArticleArchive.objects.bulk_create(...)
:
articles = list()
for article in Article.objects.filter(date__year=2011).values():
articles.append(ArticleArchive(**article))
if (len(articles) > 0):
ArticleArchive.objects.bulk_create(articles)
然后,如果你想删除原始表中的文章(可选):
Article.objects.filter(date__year=2011).delete()
答案 2 :(得分:1)
我似乎无法解决你的问题,但你可以在循环中简单地做到这一点:
obj, created = ArticleArchive.objects.get_or_create( your fields )