Hej Ken!
Iâm sorry. Thought this might be a simple solution where I just canât get my head around.
# plants/models.py
class Plant(models.Model):
name = models.CharField(
max_length=200
)
plant_type = models.ForeignKey(
PlantType,
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name="plant_type",
)
used_xducts = models.ManyToManyField(
Xduct,
through="UsedXduct",
blank=True,
related_name="used_in_plant"
)
class OperatingHour(models.Model):
plant = models.ForeignKey(
Plant,
on_delete=models.PROTECT,
related_name="operatinghour"
)
value = models.FloatField()
class UsedXduct(models.Model):
plant = models.ForeignKey(
Plant,
on_delete=models.PROTECT,
related_name="used_in_plant"
)
xduct = models.ForeignKey(
Xduct,
on_delete=models.PROTECT,
related_name="xduct"
)
class PlantType(models.Model):
name_english = models.CharField(
max_length=200
)
# xducts/models.py
class Xduct(models.Model):
code = models.CharField(
max_length=20,
unique=True,
)
name_english = models.CharField(
max_length=200,
unique=True
)
# views.py
def plants_view(request):
plants = Plant.objects.all()
myFilter = PlantFilter(request.GET, queryset=plants)
plants = myFilter.qs
context = {"plants": plants, "myFilter": myFilter}
return render(request, 'plants/search_table.html', context)
<!-- search_table.html -->
{% block content %}
<br>
<div class="row collapse {% if show_form %} show {% endif %}" id="form-holder">
<div class="row">
<div class="col">
<div class="card card-body">
<form method="get">
{{myFilter.form.as_p}}
<button class="btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Plants</h5>
</div>
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Name</th>
<th>Plant type</th>
<th>Used Xducts</th>
<th>Operating Hours</th>
</tr>
{% for plant in plants %}
<tr>
<td>{{plant.name}}</td>
<td>{{plant.plant_type}}</td>
<td>{{plant.used_in_plant}}</td>
<td>{{plant.operatinghour}}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock content %}
# filters.py
class PlantFilter(django_filters.FilterSet):
name = CharFilter(field_name="name", lookup_expr='icontains')
class Meta:
model = Plant
fields = '__all__'
plant_type and name are working fine, the used_xducts and operatinghour not.
Also the filter does work. There I can see the value and I can choose it and filter for the xduct. The result is correct.
I tried several versions in the template, like,
{{plants.used_in_plant.xduct}}
or {{plants.used_xducts.code}}
but then the field is empty and I donât even get the plants.UsedXducts.None
output.
And I checked multiple times if I have data for the plant. There should be something, as the filter can filter for that info!
Getting rather frustrated
Do you have any idea? Iâm very thankful for every idea!