Manytomany Relationships. Returning Fields In Def __str__ Method
I have two models: AffectedSegment model class AffectedSegment(models.Model): SEGMENTO_ESCAPULA = 'Escápula' SEGMENTO_HOMBRO = 'Hombro' SEGMENTO_CODO = 'Codo' SEG
Solution 1:
The problem is that self.corporal_segment_associated
is not a list of the related items, it is a ManyRelatedManager
. When you call str(self.corporal_segment_associated)
, it returns the AffectedSegment.None
string which you see in your screenshots.
To fetch the related segements, you can do self.corporal_segment_associated.all()
. This will return a queryset of the related objects. You then have to convert this queryset to a string before you use it in the __str__
method. For example, you could do:
classMovement(models.Model):
def__str__(self):
corporal_segment_associated = ", ".join(str(seg) for seg in self.corporal_segment_associated.all())
return"{},{}".format(self.type, corporal_segment_associated)
It might not be a good idea to access self.corporal_segment_associated.all()
in the __str__
method. It means that Django will do extra SQL queries for every item in the drop down list. You might find that this causes poor performance.
Post a Comment for "Manytomany Relationships. Returning Fields In Def __str__ Method"