Wednesday, January 24, 2018

One model interface to read/write to multiple models Django

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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/310c38ec-68d8-49f5-bd80-c1d247015513%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment