[Django]-Getting a value from a different class in django

2πŸ‘

You do not need to obtain the TjgFaktor through an explicit query. If you query for some_moment.typ, Django itself will perform an implcit query to fetch the TjgFaktor that corresponds to the Moment (through the foreign key), or None, if the foreign key is set to None.

We can thus query like:

def factor(self):
    tjgfaktor = self.typ
    if tjgfaktor:
        return tjgfaktor.factor

In case there is no related TjgFaktor, then this function will return None as well.

In case you define a large amount of values, then this fetch might be inefficient: Django will fetch all columns from the database, and since we are only interested in a single one, this will thus result in some overhead.

We can avoid that by using the following query:

def factor(self):
    if self.typ_id:
        return (TjgFaktor.objects.values_list('factor', flat=True)
                                 .get(pk=self.typ_id))

1πŸ‘

Assuming factor is function within Moment class, you can access factor if Moment object has related TjgFaktor object:

def factor(self):
    return self.typ.factor if self.typ else None
πŸ‘€Ivan

0πŸ‘

So, the in the factor method, you need to enter the value for typ as a string value like this: A self does not satisfy the conditions of a string parameter that is required. You could do something like this –

def factor(self):
    return TjgFaktor.objects.get(typ="YOUR_TYPE_IN_STRING").factor
πŸ‘€Druhin Bala

0πŸ‘

def factor(self):
      return TjgFaktor.objects.get(typ=self).factor

You can’t actually compare the object of Moment with objects in TjgFaktor. You can directly access the values of parent model or foreignkey directly by doing like this.

e.typ.factor #this will directly give you factor values of foreign key.

Or you can compare with

 def factor(self):
        return TjgFaktor.objects.get(typ=self.typ.id).factor
πŸ‘€Joseph

Leave a comment