How to check if variable exist in array (Template)

Hello,

I want to check if a value exists in an ArrayField in an if statement in my template.

This is my template:

{% for customer in list %}
<tr>
<!-- Checking if postalcode of the vet is in his range -->
{% if customer.postalcode in postalrepresentative.postalCodes or customer.postalcode >= postalrepresentative.beginPostalRange and customer.postalcode <= postalrepresentative.endPostalRange  %}
<td><a href="#" data-url="{% url 'customer_note' customer.id %}" class="customernote" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="las la-comment text-secondary font-16"></i></a></td>
<td>{{ customer.companyName }}</td>
{% comment %} <td>{{ customer.postalcode }}</td>
<td>{{ postalrepresentative.postalCodes }}</td> {% endcomment %}
<td>{{ customer.vetoId }}</td>
<td>{{ customer.active }}</td>
<td>{{ customer.reasonInactive }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.telephoneNumber }}</td>
<td>{{ customer.website }}</td>
<td>                                                       
 <a href="#" data-url="{% url 'customer_update' customer.id %}" class="customerupdate" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="las la-pen text-secondary font-16"></i></a>
 <a href="#" data-url="{% url 'customer_delete' customer.id %}" class="customerdelete" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="las la-trash-alt text-secondary font-16"></i></a>
</td>
{% endif %}
</tr>
{% endfor %}

My model:

### CONNECT REPRESENTATIVE WITH ZIP CODES/RANGES ###
class PostalRepresentative(models.Model):
    postalCodes = ArrayField(models.CharField(max_length=250, default= False, blank = True, null = True), blank=True, null=True)

    beginPostalRange = models.IntegerField(blank=True, null=True, default= False)
    endPostalRange = models.IntegerField(blank=True, null=True, default= False)

    representative = models.ForeignKey(User, on_delete=models.CASCADE, related_name="referentie_representative", blank=True, null=True)

And my view:

### CUSTOMERS ###
class CustomersView(FormMixin, ListView):
    template_name = 'customers/customers_overview.html'
    model = Customers
    form_class = InsertCustomerForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = self.get_form()
        context['postalrepresentative'] = PostalRepresentative.objects.get(representative = self.request.user)
        context['list'] = Customers.objects.all()
        return context
    
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self,form):
        form = form.save(commit=False)
        form.save()

        # messages.success(self.request, 'User has been added correctly.')
        return redirect('customers_overview')

    def form_invalid(self, form):
        print(form.errors)
        print("Form is invalid")
        return redirect('customers_overview')

How could you check if this value exists in this ArrayField of integers?
Thanks!

Which value are you looking to check in what list?

I’m checking customer.postalcode in postalrepresentative.postalCodes.

customer.postalcode contains an integer: 2580 and postalrepresentative.postalCodes contains an array with values: [2580, 2570, 2540].

Hope this answers your question?

In Python, it’s the in statement.
example: if customer.postalcode in postalrepresentative.postalCodes:

Really, you want to do that sort of filtering in your view and not in your template. Your view should be aggregating and filtering the data to be displayed, your template should be displaying the data being passed to it in the context.

(Side Note: Be aware that the standard Python array is different from a Python List. Confusingly enough, the PostgreSQL ArrayField is represented internally as a list. What postalCodes contains is a list, not an array.)

How would you check if a value exists inside an array in the view?

If you’re talking about an actual Python array here and not a list, then you would use the index method on the array, wrapped inside a try / except block.