6

我有这个模型类:

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]

怎么做?

4

3 回答 3

10
articles = Article.objects.filter(date__year=2011).values()
for art in articles:
    ArticleArchive.objects.create(**art)
于 2012-05-22T07:32:44.453 回答
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()
于 2014-08-20T11:42:07.660 回答
1

我似乎无法理解您的问题的核心,但您可以在循环中简单地执行此操作:

obj, created = ArticleArchive.objects.get_or_create( your fields )
于 2012-05-22T07:33:37.853 回答