How to copy an object from model A to model B

I have classes for this model:

class Article(models.Model):
    [many fields]

class ArticleArchive(models.Model):
    [same fields as Artilce model]

and I want to get objects from the article table and move them to the ArticleArchive table:

articles = Article.objects.filter(date__year=2011)
for art in articles:
    [and there moving objects]

How to do it?

+5
source share
3 answers
articles = Article.objects.filter(date__year=2011).values()
for art in articles:
    ArticleArchive.objects.create(**art)
+9
source

For best performance, it is 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 remove articles from the source table (optional):

Article.objects.filter(date__year=2011).delete()
+4
source

I could not get the crust of your problem, but you can just do it in a loop:

obj, created = ArticleArchive.objects.get_or_create( your fields )
+1
source

All Articles