Reputation: 13870
I have this model classes:
class Article(models.Model):
[many fields]
class ArticleArchive(models.Model):
[same fields as Artilce model]
and I want to get objects from Article table and move it to ArticleArchive table:
articles = Article.objects.filter(date__year=2011)
for art in articles:
[and there moving objects]
How to do it?
Upvotes: 6
Views: 2061
Reputation: 3291
For better performance, it's better to use 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)
And then, if you want to delete the articles from the original table (optional):
Article.objects.filter(date__year=2011).delete()
Upvotes: 6
Reputation: 3793
I couldn't seem to get the crust of your problem but you can simple do this in the loop:
obj, created = ArticleArchive.objects.get_or_create( your fields )
Upvotes: 1
Reputation: 798636
articles = Article.objects.filter(date__year=2011).values()
for art in articles:
ArticleArchive.objects.create(**art)
Upvotes: 10