One model interface to read/write to multiple models Django

18 views
Skip to first unread message

Chinmaya Patanaik

unread,
Jan 24, 2018, 12:30:23 PM1/24/18
to Django users
I've the following models in Django.
class User(models.Model):
       name = models.CharField(max_length=50)
       ...
       ...

    class UserInformation(models.Model):
       user = models.ForeignKey(User)
       key = models.CharField(max_length=250)
       value = models.TextField()
       ...
       ...

    class UserAddress(models.Model):
       user = models.ForeignKey(User)
       address = models.TextField(null=True)
       city = models.CharField(max_length=200)
       ...
       ...



Basically I want to create an interface for User through which I can route read and write operations to UserInformation and UserAddress.

user = User.objects.get(id=1)

    Ex - If someone wants to get all addresses of a user.
   user.get_information('address') --> This will in turn search UserAddress table and return a list of addresses.

    Ex - If someone wants to get the current age of a user.
   user.get_information('age') --> This will in turn search UserInformation table with key=age and return the value.

Similarly given a key I want to write data through the interface.

    Ex - Insert age of a user.Enter code here...

    user = User.objects.get(id=1)
   user.update_information('age', value=30) --> This will in turn insert a row in UserInformation table with key=age and value=30.


Problems:
=========
* I'm planning to create another table TableKeyMapping to keep the mapping of keys to table names. Such as if key_name=age, table_name=UserInformation. If key_name=address, then table_name=UserAddress.

What should I save in table_name..the model name UserAddress or the complete path including the the app user.models.UserAddress.

* To get data, I was planning to create a property called get_information in User model which will take key_name as a parameter. Is this the proper approach or are there any better solutions available.

* Not sure how I'll write data into separate tables. Any links or documentation will be appreciated.
Reply all
Reply to author
Forward
0 new messages