Django join tables with ForeignKey

Question:

I’m trying to join 3 tables with ForeignKey but it returns Null values. I’m using select related and also I tried Insight.objects.all() but both are not working.

Here are my models:

class schedule(models.Model):
    login_id = models.CharField(primary_key=True,max_length=20)
    agent_name = models.CharField(max_length=100, blank=True, null=True)
    team = models.CharField(max_length=100, blank=True, null=True)

class place_no(models.Model):
    place_id = models.CharField(max_length=50, blank=True,     null=True)
    pc_no =  models.CharField(max_length=50, blank=True, null=True)

class Insight(models.Model):
    login_id = models.CharField(primary_key=True,max_length=20)
    place_id = models.CharField(max_length=50, blank=True, null=True)
    agent_name = models.ForeignKey(
        schedule, on_delete=models.CASCADE,blank=True,
        null=True
    )
    pc_no = models.ForeignKey(
        place_no, on_delete=models.CASCADE,blank=True, null=True
    )

My View:

def listings(request):
data = Insight.objects.select_related('agent_name', 'pc_no')

return render(request, 'pages/listings.html', {'data':data})

{% for item in data %}
<tr>
<td class="text-center align-middle">{{ item.login_id }}</td>
<td class="text-center align-middle">{{ item.place_id }}</td>
<td class="text-center align-middle">{{ item.agent_name.agent_name }}</td>
<td class="text-center align-middle">{{ item.pc_no.pc_no }}</td>
</tr>
{% endfor %}

Asked By: Islam Fahmy

||

Answers:

Your approach is not valid. I can see, that you are thinking, that there is connection between tables with ForeignKey. Actually, there might be connection between Objects, not between whole tables.

You should not name classes with snake_case. Always use CamelCase.

To have any relation by ForeignKey you have to set it during creation or afterwards:

s = schedule.objects.create(login_id="Some login", agent_name=...)
p = place_no.objects.create(place_id="Place id", pc_no=...)

Then you can create Insight object that will be related to them:

i = Insight.objects.create(agent_name=s, pc_no=p, ...)

Then in your view/template there should be access to related objects.
PS. For early experiences with Django i recommend using Model.objects.all() or Model.objects.filter(...) instead of Model.objects.select_related(...). You can better learn and understand that way. It will be time for improvements later.

I can recommend reading official documentation.

Answered By: NixonSparrow

I solved my problem by the below, I could update the DB with the result of the below query

    cursor = connection.cursor()
    cursor.execute('''
    UPDATE Insight
        SET agent = ( SELECT agent_name FROM schedule
            WHERE Insight.login_id = schedule.login_id ) ''')
Answered By: Islam Fahmy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.