Luca
Luca

Reputation: 11016

How to get the model column value from the foreign key

I am trying to learn Django and I have a simple model like:

class Document(models.Model):
    labelled_image = models.ForeignKey(LabelModel, db_column='label')

So this refers to another model(LabelModel), which is defined as:

class LabelModel(models.Model):
    image = models.FileField(upload_to='documents/label',
                             db_column='path', default='Some Value')

Now, at some point I save an instance of a Document model and I get hold of the primary key. So, I can get the model instance by:

obj = Document.objects.filter(pk=document_id)

Now, my question is how can I get the actual value of the corresponding image in the LabelModel that the foreign key points to? In database pseudocode I would have something like (I have not done this in a while):

SELECT path from label_table where id=obj.labelled_image

and this would return me the path string from the database.

Upvotes: 0

Views: 161

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600049

Firstly, you must use get not filter in your original query to get the Document:

obj = Document.objects.get(pk=document_id)

because filter always returns a queryset, even if there is only one matching object.

Now you have obj, you can just use the normal dot notation to get the attribute:

obj.labelled_image

This returns the relevant instance of LabelModel, and obj.labelled_image.image will return the value of the file field.

Upvotes: 1

Related Questions