0

I have two tables (say Parent and Child). I want parent and Child to link to each other using a foreign key. The child table has two fields, one among them being 'country_sig'. This country_sig is actually made from joining two fields in parent table named 'country' and 'code'. Eg: If country is 'IN' and code is '15' then country_sig is IN.15.

Now I want that during creation of django model for parent table, it should automatically create this field country_sig derived from 'country' and 'code' so that I can reference it to the child table.

PS : Since the parent table is very large, I don't want to create another field in the db derived from those two fields, but I can tweak the other table (child table) to divide the country_sig field into two columns with 'country' and 'code' but that will not work since django does'nt support composite primary key.

EDIT: Actually I am implementing it in tastypie, I want tastypie to think as if it is a real field. This would solve my real problem.

pranavk
  • 1,774
  • 3
  • 17
  • 25
  • I am not sure what you mean with referencing to each other. Do you want to dynamically add this combined field so you can query it from the child table? – RickyA Jul 12 '12 at 19:46
  • because i am implementing it in tastypie, (question edited) – pranavk Jul 12 '12 at 20:02
  • So you want tasypie to output this combined field in the parent resource? – RickyA Jul 12 '12 at 20:04
  • i am doing something that involves making tastypie fool in assuming that a real field exist in the table but actually it doesn't. Ya, outputting this combined field with tastypie in parent resource. – pranavk Jul 12 '12 at 20:06

1 Answers1

0

Perhaps don't use the standard tasypie ModelResources, but write your own resource:

class DictWrapper(object):
    '''
    to be used as generic tastypie resource object 
    '''
    def __init__(self, initial=None):
        self.__dict__['_data'] = {}

        if hasattr(initial, 'items'):
            self.__dict__['_data'] = initial

    def __getattr__(self, name):
        return self._data.get(name, None)

    def __setattr__(self, name, value):
        self.__dict__['_data'][name] = value

    def to_dict(self):
        return self._data

class ParentResource(Resource): 
    def get_object_list(self, request):        
        ret = []
        for parent in Parent.objects.all():
            ret.append(DictWrapper({"country_sig":"{0}.{1}".format(parent.country, parent.code})))
        return return

    def obj_get_list(self, request=None, **kwargs):      
        return self.get_object_list(request)
RickyA
  • 15,465
  • 5
  • 71
  • 95