DJANGO ForeingKey selection from the reference table depending on the user

Section -> Complexes -> Line -> Equipment -> Report

I need to make sure that when adding a Report, only the equipment Section to which the user belongs and status=true is in the Equipment list. I just started learning Django. Tell me what you need to look at to solve this problem.

`class Section(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...)
        name = models.CharField(max_length=30, blank=True, ...)
    def __str__(self):
        return self.name 

class Complexes(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...)
    name = models.CharField(max_length=30, blank=True, ...)
    section = models.ForeignKey(Section, on_delete=models.SET_NULL, ...)
    def __str__(self):
        return self.section.__str__()+" "+self.name   

class Line(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...)
    name = models.CharField(max_length=30, blank=True, ...)
    complexes = models.ForeignKey(Complexes, on_delete=models.SET_NULL, ...)
    def __str__(self):
        return self.complexes.__str__()+" "+self.name

class Equipment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...)
    name = models.CharField(max_length=30, blank=True, ...)
    line = models.ForeignKey(Line, on_delete=models.SET_NULL, ...)
    status = models.BooleanField(default=True, ...)
    ...
    def __str__(self):
        return self.name +" "+ self.explanation +" "+ self.line.__str__()

class Report(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...)
    equipment = models.ForeignKey(Equipment, on_delete=models.DO_NOTHING, ...)
    ...`

There are two components at play - the database, and the website the user interacts with. The model defines the database but it should not define anything about the website. But your question is phrased in such a way that you're asking what you can do about models to change what happens on the website - this is generally speaking a category error.

If you're trying to change what is visible to the user, your functionality of selecting the proper set of Equipment belongs in a view.

Assuming that user.section is a relationship from User to Section, your selection of items within the view can look like this:

user = request.user
queryset = Equipment.objects.filter(
    status=True,
    line__complex__section=user.section
)

If you're confused by the syntax on the last line, it's simply Django's convention for how to traverse model relationships.

Back to Top