Swathi Pantala
Swathi Pantala

Reputation: 355

Insert QuerySet results in a table in Django which have same fields

I have a QuerySet which will have the information from some x-table and now I want to insert these values into another table which have same fields as of x-table.

Upvotes: 2

Views: 1044

Answers (1)

ilse2005
ilse2005

Reputation: 11429

If models A and B have the exact same fields, you can do something like this:

a_objects = A.objects.all()
# loop over objects
for a in a_objects:
    # convert a to dictionary
    a_dict = a.__dict__
    a_dict.pop('id')   # remove primary key from dict
    # create B model
    B.objects.create(**a_dict)

You can look here for other ways to convert a model to a dictionary.

Upvotes: 3

Related Questions