How to retrieve an object or a particular field from context object in view?

126 views Asked by At

My code is below: dept_id and desi_id is the field of entries3 views.py

def claim(request):
    entries = Child_Info.objects.all()
    entries2 = Employee.objects.filter(emp_name='Suresh Babubhai Vekariya')
    entries3 = Emp_Department.objects.filter(emp_no=12345)
    for a in entries3:
        dept_id = a.dept_id;
        desi_id = a.desi_id

    print dept_id
    ctx = { 'entries' : entries ,'entries2' : entries2 }

    return render_to_response('myapp/claim.html', ctx)

Here are that 3 models:

class Department(models.Model):
    dept_id = models.CharField(primary_key=True,max_length=20,unique=True)
    dept_name = models.CharField(max_length=20)
    dept_add = models.CharField(max_length=30)
    def _str_(self):
    return self.dept_id

class Emp_Department(models.Model):
    emp_no = models.ForeignKey(Employee)
    dept_id = models.ForeignKey(Department)
    emp_type = models.CharField(max_length=30)
    desi_id =  models.CharField(max_length=30)
    join_date = models.DateField()
    retire_date = models.DateField()

def _str_(self):
    return "%s,%s,%s" %(self.desi_id,self.dept_id,self.emp_no)

class Designation(models.Model):
    desi_id = models.CharField(primary_key=True,max_length=30)
    dept_id = models.ForeignKey(Department)
    title = models.CharField(max_length=20)

def _str_(self):
    return "%s,%s,%s" %(self.desi_id,self.dept_id,self.title)

I want to fetch title from designation and dept_name from Department

1

There are 1 answers

2
Animesh Sharma On

You have already filtered the results on the basis of a particular field.

entries3 = Emp_Department.objects.filter(emp_no=12345)

In case you are trying to ask as to how to display a particular field in the template then in your claim.html file, try the following:

{{entries2.0.emp_name}}

This will display the emp_name of the first employee. Similarly, you can replace emp_name with whatever field you want to display inside the template.

I hope this is what you wanted to ask because the question is not quite clear.