0

let's suppose i have two models like below:

class Client(models.Model):
    login = models.CharField(max_length=100)
    password = models.CharField(max_length=100)

class Users(models.Model):
    user_login = models.CharField(max_length=100)
    user_pass = models.CharField(max_length=100)

One model [Users] is filled with data, second [Client] is empty. First i can populate Client based on Users. Now all Django data changes will by held only on Client model.

Question:

How to dynamically connect this two models fields? For example if some data is changed on model Client then according data will by changed also on Users model.

Solution suggestion:

I can update or populate Client data and simultaneously update or populate Users data. Is there another solution to do this?

Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38

2 Answers2

0

if login is unique then no need to maintain foreign key relations, You can override the save() methods in both models else You have to maintain the foreign key relation and override the save() methods.

0

With help of this post i manage to link two models with below code:

class Client(models.Model):
    login = models.CharField(max_length=100)
    password = models.CharField(max_length=100)

    # save previous instance
    def __init__(self, *args, **kwargs):
        super(Invoice, self).__init__(*args, **kwargs)
        self.original_login = self.login

    # override save method to update another model fields
    def save(self, *args, **kwargs):
        # import in place to avoid circular imports
        from app.models import Users

        if self.login != self.original_login:
            Users.objects.filter(id=self.id).update(user_login=self.login)

        # save changed data on Client model
        super(Client, self).save(*args, **kwargs)

The same method goes to the Users model. Note that this two model are in different apps.

Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38