I'm a Django Beginner and I was dealing with same problem as in :(How to display Foreignkey table Data in Django?) but the solution to mine was pretty simple which left me to wonder HOW? And even after I got rid of the problem I've a query .
My Models were :
class Customer(models.Model):
name = models.CharField(max_length=64, unique=False)
cust_id = models.CharField(max_length=10, unique=True)
class Employee(models.Model):
name = models.CharField(max_length=64, unique=False)
salary = models.BigIntegerField()
emp_id = models.CharField(max_length=10, unique=True)
class Order(models.Model):
order_id = models.CharField(max_length=64, unique=True)
assigned_to = models.ForeignKey(to=Employee, on_delete=models.CASCADE)
given_by = models.ForeignKey(to=Customer, on_delete=models.CASCADE)
bill = models.IntegerField(null=False)
As you can see my Order model contains " assigned_to " so in HTML template I wrote it as :
{% for x in my_orders %}
<tr>
<td>{{ x.assigned_to }}</td>
</tr>
{% endfor %}
and all I was getting a blank space I went to shell and get the queryset which showed it as "assigned_to_id" instead of "assigned_to". and then changing in HTML as :
{% for x in my_orders %}
<tr>
<td>{{ x.assigned_to_id}}</td>
</tr>
{% endfor %}
worked for me. Why is that?
CodePudding user response:
because you didn't set a return for the Employee Model.
You can do something like that to your Employee model.
class Employee(models.Model):
name = models.CharField(max_length=64, unique=False)
salary = models.BigIntegerField()
emp_id = models.CharField(max_length=10, unique=True)
def __str__(self):
return f"self.name"
Then in your template you will receive the name. If you want to access any other field then you need to use the _
as you used after the name of the field
assigned_to_id
assigned_to_name
assigned_to_salary
assigned_to_emp_id