[Django]-How to save ManyToMany field in second database

1👍

django does not support cross database relations.

Extract from cross database relations

Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.

However, as explained here you can implement post_save signal for user to have same user record on slave database. But you will have to maintain that database consistency e.g. deleting user from both databases.

Update: to save ManyToMany in different db you can try this

for i in Data.objects.all():
    back_i = i
    i.save(using='slave')
    for u in back_i.users.all():
        i.users.add(u)
👤Rohan

0👍

A little modification to rohan’s idea… (it is assumed that ‘User’ already exists in slave database)

for item in Data.objects.all():

    new_item = item
    item_users = item.users.all()

    new_item.save(using='slave')

    for u in item_users:
       u2 = User.objects.using('slave').get(pk=u.id)
       new_item.users.add(u2)

    new_item.save(using='slave')
👤jjorda

Leave a comment