Home > Software design >  Django FIlter: Filtering object hidden in multi layered model structure
Django FIlter: Filtering object hidden in multi layered model structure

Time:04-30

I have a following django model relationship:

class Project(models.Model):
    pass 
class Vehicle(models.Model):
    project=ForeignKey(Project) 
class Concept(models.Model):
    vehicle=ManyToManyField(Vehicle) 
class Analysis(models.Model):
    concept=ForeignKey(Concept)

I want to sort out all Analyses objects which are connected to a Project with a known id. Concept can be for more than one vehicle but all the vehicles within a concept will be limited to only one Project. Or should i justadd to all following models a foreignkey with a project field?

Thanks

CodePudding user response:

You can .filter(…) [Django-doc] with:

Analysis.objects.filter(concept__vehicle__project_id=project_id)

It is possible that a Concept has many Vehicles that point to the same Project, and in that case the Analysis will be duplicated. You can use .distinct() [Django-doc] to prevent this:

Analysis.objects.filter(concept__vehicle__project_id=project_id).distinct()

Note: Since a ManyToManyField refers to a collection of elements, ManyToManyFields are normally given a plural name. You thus might want to consider renaming vehicle to vehicles.

  • Related