B
B
Bojczuk2015-11-24 16:04:45
Django
Bojczuk, 2015-11-24 16:04:45

How to get field value from linked model?

The two classes are linked via ForeignKey:

#Class1:
field1 = models.ForeignKey('Class2', null=True, blank=True)

As far as I understand the following code should give me a Class2 object, but I only get the value:
c = Class1.objects.get(id=1)
c.field1 #значение таблицы Class1 вместо объекта Class2
c._meta.get_field('field1').rel.to #Class2

What could be the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
Bojczuk, 2015-11-25
@Bojczuk

The ForeignKey parameter passed the name of the model as a string, not its object. The documentation says that this is possible in the case for yet undefined models, but not in mine.

field1 = models.ForeignKey(Class2, null=True, blank=True)

R
Roman Kitaev, 2015-11-24
@deliro

c.field1 gives you an object, not a table value.
If you need the class itself and not the object, you can do type(c.field1)

S
Sergey Eremin, 2015-11-24
@Sergei_Erjemin

Through a double underscore...
I.e. something likec.get_field('field1__поле_из_связной_таблицы')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question