How to deal with empty foreign keys in a for loop within django View

Viewed 30

I have a model which acts a as schedule where there are multiple FK relationships to the same user table. All of these fields can be blank/null.

The issue is, when i do a for loop, i am trying to match the users based on when they appear on a certain shift, then add a +1 to a counter to get the total shifts for that user.

The model looks like this:

class WeekdayAssignment(models.Model):
    """Model definition for WeekdayAssignment."""

    start_date = models.DateField(auto_now=False, auto_now_add=False)
    end_date = models.DateField(auto_now=False, auto_now_add=False)
    triage_emea_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_emea_1", blank=True, null=True)
    triage_nam_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_1", blank=True, null=True)
    triage_nam_2 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_2", blank=True, null=True)
    triage_nam_3 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_3", blank=True, null=True)
    ...

As you can see i have 4 triage shifts and the same user can work any of those shifts.

I want to do a for loop to count how many times a user is on a shift in any one of those fields.

Without getting into all the details of what I am doing, i will keep it simple as the error happens right away.

Views.py

def someview(request):
    shift_users = TeamMember.objects.all()
    weekday_shifts = WeekdayAssignment.objects.all()
    for t in shift_users:
        for ws in weekday_shifts:
            print(ws.triage_nam_3)

As long as there is a value in the field, this will print fine but if the field is empty (i.e. no users selected for that field) it fails with TeamMember matching query does not exist.

I have tried to do check if None but it gives the same problem. Now this error goes away once I populate a user but how can i check if it's empty and just skip it?

Thanks in advance.

1 Answers

You can catch models.DoesNotExist exception.

def someview(request):
    shift_users = TeamMember.objects.all()
    weekday_shifts = WeekdayAssignment.objects.all()
    for t in shift_users:
        for ws in weekday_shifts:
            try:
                print(ws.triage_nam_3)
            except TeamMember.DoesNotExist:
                continue
Related