2

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.

Swathi Pantala
  • 335
  • 1
  • 6
  • 13

1 Answers1

3

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.

Community
  • 1
  • 1
ilse2005
  • 11,189
  • 5
  • 51
  • 75