So I have two models Field and Sensor which have a OneToMany connection. Im creating a page where I have all the fields and whenever i click on one i get its respective sensors. I've made 4 test sensors (3 of them are on Field1, 1 on Field2) but its printing first one to first field and 2nd one to 2nd field maybe because of the pk parameter. Any clue how to fix that ?
class Field(models.Model):
friendly_name = models.CharField(max_length=24, blank=True)
soil_type = models.CharField(max_length=24, choices=SOIL_TYPES, blank=True)
cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True)
class TreeSensor(models.Model):
field = models.ForeignKey(Field, on_delete=models.CASCADE)
datetime = models.DateTimeField(blank=True, null=True, default=None)
sensor_name = models.CharField(max_length=200, blank=True)
longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
View :
def detail(request, field_id):
try:
sensor = models.TreeSensor.objects.get(pk=field_id)
except models.TreeSensor.DoesNotExist:
raise Http404("No sensors for this field")
return render(request, 'dashboard/detail.html', {'sensor': sensor})
html:
<h1> {{ field.friendly_name}}</h1>
{% for sensor in field.treesensor_set.all %}
{{treesensor.sensor_name}}
{%endfor%}
CodePudding user response:
I'm not sure what does this line will print out? and what is "models" in that case mean!
models.TreeSensor.objects.get(pk=field_id)
however, if you passed field_id which means the id of the Field model so, I think you can replace that filtering instead:
TreeSensor.objects.filter(field__pk=field_id)
CodePudding user response:
Yeah that seemed to do the trick I also changed my template
{% for sensor in sensor %}
<ul>
<li>{{ sensor.sensor_name}}</li>
</ul>
{%endfor%}
and view :
def detail(request, field_id):
try:
sensor = models.TreeSensor.objects.filter(field__pk=field_id)
except sensor.DoesNotExist:
raise Http404("No sensors for this field")
return render(request, 'dashboard/detail.html', {'sensor': sensor})
I get the right sensors on the right fields but if a field is empty the http404 does not raise an error.
Maybe I'm doing something wrong with the does.not.exist
?How to just check for an empty query and print out the corresponding text? Thanks