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
- [Django]-Django "manage.py index" does not execute as a cron job
- [Django]-Django modify bridge table
- [Django]-DRF serializer's BooleanField returns null for empty ForeignKey field
- [Django]-Django: 'User' object has no attribute 'user'
- [Django]-How to get title, artist, and album art using mutagen (Python and Django)?
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
- [Django]-Fixture not found pytest
- [Django]-Spotify API authentication with Python
- [Django]-Extract only values without key from QuerySet and save them to list
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
- [Django]-Copying files from one model to another
- [Django]-CouchDB write/read only (no edit) user
- [Django]-"Not a valid string." β error when trying save dict to TextField in Django Rest Framework
- [Django]-Django serving each app separately in each its port
- [Django]-Django reference url in views.py