Gradatc
Gradatc

Reputation: 125

Django: Get distinct values from a foreign key model

Django newbie, so if this is super straightfoward I apologize.

I am attempting to get a listing of distinct "Name" values from a listing of "Activity"s for a given "Person".

Models setup as below

class Activity(models.Model):

Visit = models.ForeignKey(Visit)
Person = models.ForeignKey(Person)
Provider = models.ForeignKey(Provider)
ActivityType = models.ForeignKey(ActivityType)
Time_Spent = models.IntegerField(blank=True, null=True)
Repetitions = models.CharField(max_length=20, blank=True, null=True)
Weight_Resistance = models.CharField(max_length=50, blank=True, null=True)
Notes = models.CharField(max_length=500, blank=True, null=True)


class ActivityType(models.Model):

Name = models.CharField(max_length=100)
Activity_Category = models.CharField(max_length=40, choices=Activity_Category_Choices)
Location_Category = models.CharField(max_length=30, blank=True, null=True, choices=Location_Category_Choices)

I can get a listing of all activities done with a given Person

person = Person.objects.get(id=person_id)
activity_list = person.activity_set.all()

I get a list of all activities for that person, no problem.

What I can't sort out is how to generate a list of distinct/unique Activity_Types found in person.activity_set.all()

person.activity_set.values('ActivityType').distinct()

only returns a dictionary with

{'ActivityType':<activitytype.id>}

I can't sort out how to get straight to the name attribute on ActivityType

This is pretty straightforward in plain ol' SQL, so I know my lack of groking the ORM is to blame.

Thanks.

Update: I have this working, sort of, but this CAN'T be the right way(tm) to do this..

distinct_activities = person.activity_set.values('ActivityType').distinct()
uniquelist = []
for x in distinct_activities:
    valuetofind = x['ActivityType']
    activitytype = ActivityType.objects.get(id=valuetofind)
    name = activitytype.Name
    uniquelist.append((valuetofind, name))

And then iterate over that uniquelist...

This has to be wrong...

Upvotes: 0

Views: 981

Answers (1)

sebb
sebb

Reputation: 1976

unique_names = ActivityType.objects.filter(
    id__in=Activity.objects.filter(person=your_person).values_list('ActivityType__id', flat=True).distinct().values_list('Name', flat=True).distinct()

This should do the trick. There will be not a lot of db hits also. Writing that down from my phone, so care for typos.

Upvotes: 2

Related Questions