One To Many Connection

Im new to Django. 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):

    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None)

    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%}

Your view does not appear to match the template you’re showing.

The view is creating a context with an identifier named sensor, but you are not using sensor in that template.

Yeah sry thats a typo I’ve changed that already but the issue doesnt come from there . I still get the same response I explained . ( showing sensor with id=1 to field with id =1 etc.)

Please post your updated code then. (You don’t need to edit the original post, just add the updated versions in your next reply.)

I’ve tried using

def detail(request, field_id):
        try:
            sensor = models.TreeSensor.objects.get(field = models.Field.friendly_name)
        except models.TreeSensor.DoesNotExist:
            raise Http404("No sensors for this field")
        return render(request, 'dashboard/detail.html', {'sensor': sensor})

and

{% if field.friendly_name == treesensor.sensor_name%}
{% for sensor in sensor %}
       {{sensor}}
    {%endfor%}

{%endif%}

and i get the 404 error message.Basically what is the correct objects.get i should use and the corresponding template so it does print each sensor assigned to each field.

Review the docs at Writing views | Django documentation | Django. Pay particular attention to the examples and how models are imported and accessed in the views. You can also review the information at Writing your first Django app, part 3 | Django documentation | Django

I went through those thats how i came up with the original code but i still cant figure out the correct way

This is the reference i used for my own template
https://docs.djangoproject.com/en/4.0/intro/tutorial03/#use-the-template-system

First, let’s back up to your original post. It’s a lot closer to being correct than this last attempt.

So roll your code back to the original, with the only change being to fix the reference name in your context.

Post that, and we’ll work forward from there.

{sensor}}

  {% comment %}   {% for sensor in field.sensors_set.all %}
    <ul>
        <li>  {{ sensors.sensor_name}} </li>
   {%endfor%} {% endcomment %}
    </ul>

Im onlu using the {{sensor}} to print ,the rest is another method i tried from the tutorial but doesnt work . So sensor prints out sensor1 for field1 sensor2 for field2 etc because of the pk=field_id call i think even though first two are in field1. Instead i want to match the sensors to their right fields.

Figured it out

    {% for sensor in sensor %}
    <ul>
        <li>{{ sensor.sensor_name}}</li>
    </ul>
    {%endfor%}

and

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})

prints the right sensors on the right fields but now i cant get a 404 response from the view. Any way i can print that message? Im probably doing something wrong with the doesnotexist

The DoesNotExist error is thrown on the Model, not the instance - in this case, it would be TreeSensor.DoesNotExist.