Search code examples
djangodjango-modelstastypie

Joining unrelated models and filter the queryset


I have the following Models I would like to join:

Datapoint

class Datapoint(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition', blank=True, null=True)  # Field name made lowercase.
    value = models.IntegerField(db_column='Value')  # Field name made lowercase.

Composition

class Composition(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    name = models.CharField(db_column='Name', max_length=45, blank=True, null=True)  # Field name made lowercase.

DataComponent

class Datacomponent(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition_ID', null=True, blank=True)  # Field name made lowercase.
    components = models.ForeignKey(Components, models.DO_NOTHING, db_column='Components_ID')  # Field name made lowercase.
    componentvalue = models.FloatField(db_column='ComponentValue')  # Field name made lowercase.

And finally, Component

class Components(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    name = models.CharField(db_column='Name', max_length=45, blank=True, null=True)  # Field name made lowercase.

Each datapoint contains a foreign key to the composition table. Datapoint and Composition tables are hence related. Each composition has many components which is linked by composition field in Datacomponent table which also contains components foreign key to the Component table.

The end goal is to build a list of Datapoint objects filtered by a particular component value in Datacomponents table.

For instance lets say we have a number of datapoints. If we just have 2 Compositions A and B. A contains 2 elements AA and BB with values being 30 and 50 respectively. B contains 3 elements AA BBB and CC with values 40, 50, and 60 respectively. One example query in this scenario would be - Fetch all datapoints with Component AA's value more than 30.

Since Datacomponent is not directly linked with Datapoint, I am not sure how to combine these two models. Currently I am trying to build this in get_object_list of tastypie library.

Any help would be highly appreciated.


Solution

  • You can follow the relationships through as many levels as you like. Remember to always start from the class whose objects you need. For your example query, it would look something like:

    Datapoint.objects.filter(
        composition__datacomponent__component_value__gte=30,
        composition__datacomponent__components__name='AA'
    )