Search code examples
djangojoindjango-modelsinner-join

Access values from joined table in django


I have 2 tables linked together by a foreign key (Category, Activity). I'm trying to access the values in the category table from my query using the activity object.

Model class:

class Category(models.Model):
name = models.CharField(max_length=100)
weekly_goal = models.IntegerField(blank=True, null=True)
metacat_fk = models.ForeignKey(MetaCategory, models.DO_NOTHING, db_column='metacat_fk')

class Meta:
    managed = False
    db_table = 'category'


class Activity(models.Model):
name = models.CharField(unique=True, max_length=100)
distance = models.FloatField(blank=True, null=True)
duration = models.TimeField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
note = models.CharField(max_length=100, blank=True, null=True)
category = models.ForeignKey(Category, models.DO_NOTHING, db_column='category_fk')

class Meta:
    managed = False
    db_table = 'activity'

Trying to access the values in Category:

activity = Activity.objects.select_related('category')
frequency_df = pd.DataFrame(list(activity.values()))

logging.warning(activity.query)
logging.warning(frequency_df.head())

Output:

SELECT "activity"."id", "activity"."name", "activity"."distance", "activity"."duration", "activity"."date", "activity"."note", "activity"."category_fk", "category"."id", "category"."name", "category"."weekly_goal", "category"."metacat_fk" FROM "activity" INNER JOIN "category" ON ("activity"."category_fk" = "category"."id")

     id                                name distance duration        date  note  category_id
     0  1382       Yoga - Wednesday June 19 2019     None     None  2019-06-19  Yoga            3
     1  1385  Yoga - Wednesday September 18 2019     None     None  2019-09-18  Yoga            3
     2  1388      Yoga - Tuesday October 08 2019     None     None  2019-10-08  Yoga            3
     3  1391      Yoga - Tuesday October 15 2019     None     None  2019-10-15  Yoga            3
     4  1394     Yoga - Saturday October 26 2019     None     None  2019-10-26  Yoga            3

According to my query, it is selecting values from my category table, but my Activity object only contains my FK. I would expect the output to have columns for category.name category.weekly goal ect...


Solution

  • If you want the related values, you need to define them explicitly.

    activity = Activity.objects.select_related('category')
    activity_values = activity.values(
        "id", "name", "distance", [...], 
        "category__name", "category__weekly_goal", "category__metacat_fk__name"
    )
    frequency_df = pd.DataFrame(list(activity_values))