[Django]-ManyToMany Relationships. Returning fields in def __str__ method

6πŸ‘

βœ…

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:

class Movement(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.

πŸ‘€Alasdair

Leave a comment