简体   繁体   中英

How to serialize multiple models data in django-rest when models classes are generated from legacy database

  1. Model classes are generated from existing database, do not show foreign keys relation in generated model classes.

     $ python manage.py inspectdb $ python manage.py inspectdb > models.py 
  2. Goal is to get related data from multiple tables.

  3. Following is my serializer snippet:

     from .models import JobsList, JobsCategories class JobsCategoriesSerializer(serializers.ModelSerializer): class Meta: model = JobsCategories fields = ('name', 'id',) class JobsListSerializer(serializers.ModelSerializer): category = JobsCategoriesSerializer(source='job_category', many=True) class Meta: model = JobsList fields = ('job_title', 'category') 
  4. Error: Request Method: GET Request URL: http://localhost:8000/jobs/6 /?access_token=bBN6BSLlYi8TXF3SkLEOMbtsKfD3xX&format=json Django Version: 1.8.3 Exception Type: TypeError Exception Value:

    'long' object is not iterable

5.1 The response is:

{"id":6,"userid":491,"company_id":4,"job_title":"Web Designer","job_info":"We require a web designer.","min_exp":0,"max_exp":1,"min_ctc":null,"max_ctc":null,"open_positions":0,"location":"18","hr_email":"","contact_number":"","job_category":3,"job_referred":"0","added_by":"0","status":"1","date_time":null,"expiry_date":null,"job_meta":"web graphics bodhan designer funvestfinancials","job_type":"0"}

** I want job_category which is an id replaced with category name**

  1. I need help to get category name with job data jobs_category and jobs_list are two separate model classes generated by reverse engineering from existing database. Kindly help me if this is possible in this way I am doing or if it is doable in another.

  2. Job list model:

     class JobsList(models.Model): ..... job_category = models.IntegerField(blank=True, null=True) ..... 
  3. Category model:

     class JobsCategories(models.Model): name = models.CharField(max_length=255) status = models.CharField(max_length=1) class Meta: managed = False db_table = 'jobs_categories' def __unicode__(self): return '%s' % (self.name) 

    ** I need categories name whose id is in job_category column jobs_list table. Issue is the model classes generated from legacy database do not have relations **

You can override the to_representation() method of the JobsListSerializer to get your desired response.

You need to do something like:

class JobsListSerializer(serializers.ModelSerializer):
    class Meta:
        model  = JobsList
        ...

    def to_representation(self, obj):
        serialized_data = super(JobsListSerializer, self).to_representation(obj) # original serialized data
        job_category_id = serialized_data.get('job_category') # get job category id from original serialized data
        job_category = JobsCategories.objects.get(id=job_category_id) # get the object from db
        serialized_data['job_category'] = job_category.name # replace id with category name
        return serialized_data # return modified serialized data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM