user3737366
user3737366

Reputation: 3

how to sort two table data in django

models.py

class Engineer(models.Model):
    full_name = models.CharField(max_length=60, unique = True)

    def __unicode__(self):
        return '%s,%s'% (self.id,self.full_name)

class TestcaseCache(models.Model):
    name = models.CharField(max_length=60)
    package_name = models.CharField(max_length=100)
    summary = models.TextField()
    pre_requisite = models.TextField(blank = True,null=True)
    author_id = models.ForeignKey(Engineer, related_name = 'author')

views.py

Here i want to sort the testcasecache data by author name but in testcasecache table there is foreign key of engineer table not name of the engineer and i want to sort testcasecache table by engineer name

global flag
if flag==0:                       
    testcase_object_array=TestcaseCache.objects.filter(project=pid).filter(feature=fid).order_by('-author_id')
    flag=1
else:
    flag=0                
    testcase_object_array=TestcaseCache.objects.filter(project=pid).filter(feature=fid).order_by('author_id')

Upvotes: 0

Views: 65

Answers (1)

iskorum
iskorum

Reputation: 1137

you can use two underscore for related lookups;

TestcaseCache.objects.filter(project=pid).filter(feature=fid).order_by('author_id__name')

or

TestcaseCache.objects.filter(project=pid).filter(feature=fid).order_by('-author_id__name')

Advice: don't use id for foreign keys, I mean use author not author_id. filter can take all parameters;

TestcaseCache.objects.filter(project=pid, feature=fid).order_by('author__name')

Upvotes: 1

Related Questions