user1367204
user1367204

Reputation: 4797

Django: how to load a Queryset with a specific field of a foreign key?

I have 2 models, Painting and Painter.

 class Painting(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()
    painter = models.ForeignKey(Painter)


 class Painter(models.Model):
    name = models.CharField(max_length=200)
    code = models.CharField(max_length=200)

In reality, Painting has 30 columns and Painter has 3.

How can get a QuerySet of paintings so that instead of each object having a painter_id it has painter_name?

I've tried many variations of:

paintings = Painting.objects.prefetch_related('painter_set__name').all()

but can't seem to get it right.

My ultimate goal is to use pandas to export a CSV, so I want each object in the QuerySet to have all the fields I'm interested in.

I want to do something like

paintings = Painting.objects....
df = pandas.DataFrame(list(paintings.values()))
df.to_csv('blah.csv’)

Upvotes: 1

Views: 565

Answers (1)

Brian Destura
Brian Destura

Reputation: 12078

One way to support this is to annotate each row with the related painter name using F expressions like this:

from django.db.models import F

paintings = Painting.objects.annotate(painter_name=F('painter__name')).all()

Each painting instance in the paintings list will have a painter_name attribute based on the related painter's name field.

Upvotes: 1

Related Questions