0

The following is in my models.py:

class SensorType(models.Model):
    hardware_type  = models.CharField(max_length=100)
    is_static = models.BooleanField(default=False)
    # Some other fields

class Sensor(models.Model):
    device_id = models.CharField(max_length=100, primary_key=True)
    sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT)
    # Some other fields

class Asset(models.Model):
    name = models.CharField(max_length=100)
    sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT) # I need to use this field to filter below
    sensor = models.ForeignKey(Sensor, on_delete=models.PROTECT, limit_choices_to={'sensor_type': WHAT DO I PUT HERE?},)
    # Some other fields

I need to limit the choices in the sensor field of asset so that only sensors with the sensor_type set in the field immediately above, show up.

The reasoning behind this is that there will eventually be many sensors and it would be very useful to filter this. Initially I only need this to work from the admin page but this will eventually extend when I make my Create and Update Views.

Is this even possible? I'm essentially trying to access attributes before the object has actually been created.

After reading several other questions such as this one I have also looked into ModelChoiceField but the same issue exists of trying to access the form data before it has been submitted.

I'm very open to changing the model structure if that is what is required.

  • This package may be of interest to you https://django-autocomplete-light.readthedocs.io/en/master/. Docs regarding filtering choices based on other fields https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#filtering-results-based-on-the-value-of-other-fields-in-the-form – Iain Shelvington Jan 18 '22 at 17:03
  • @IainShelvington Thank you! This is exactly what I need for forms in the front end! I can't quite work out how to replicate that behavior in the admin panel. I would need to customize the admin site to use those forms wouldn't I? – Space Otter Jan 19 '22 at 14:43

0 Answers0