ManyToMany Relationships. Returning fields in def __str__ method

爱⌒轻易说出口 提交于 2021-01-27 19:17:24

问题


I have two models:

AffectedSegment model

class AffectedSegment(models.Model):

    SEGMENTO_ESCAPULA = 'Escápula'
    SEGMENTO_HOMBRO = 'Hombro'
    SEGMENTO_CODO = 'Codo'
    SEGMENTO_ANTEBRAZO = 'Antebrazo'
    SEGMENTO_CARPO_MUNECA = 'Carpo/Muñeca'
    SEGMENTO_MANO = 'Mano'
    SEGMENT_CHOICES = (
        (SEGMENTO_ESCAPULA, u'Escápula'),
        (SEGMENTO_HOMBRO, u'Hombro'),
        (SEGMENTO_CODO, u'Codo'),
        (SEGMENTO_ANTEBRAZO, u'Antebrazo'),
        (SEGMENTO_CARPO_MUNECA, u'Carpo/Muñeca'),
        (SEGMENTO_MANO, u'Mano'),
    )

    affected_segment = models.CharField(
        max_length=12,
        choices=SEGMENT_CHOICES,
        blank=False,
        verbose_name='Segmento afectado',
        help_text='Ingrese uno o mas segmentos corporal de miembros superiores'
    )

    class Meta:
        verbose_name_plural = 'Segmentos corporales'

    def __str__(self):
        return "%s" % self.affected_segment

And Movement model. Please review the __str__ method of this model at the end:

class Movement(models.Model):
    type = models.CharField(
        max_length=255,
        verbose_name='Tipo de movimiento'
    )

    corporal_segment_associated = models.ManyToManyField(
        AffectedSegment,
        blank=True,
        verbose_name='Segmento corporal asociado')

    class Meta:
        verbose_name = 'Movimiento'

    def __str__(self):
        return "{},{}".format(self.type, self.corporal_segment_associated)

I have another model named RehabilitationSession in which I want allow the possibility of choose multiple affected_segments and multiple movements such as follow:

class RehabilitationSession(models.Model):

affected_segment = models.ManyToManyField(
    AffectedSegment,
    verbose_name='Segmento afectado',
    #related_name='affectedsegment'
)
movement = models.ManyToManyField(
    Movement,  # Modelo encadenado
    verbose_name='Movimiento',
    #related_name = 'movement'
)

In my Django Admin when I go to the RehabilitationSession model I see the following in the movement field:

I understand that in the ManyToMany relationships, a intermediate table is created with the ID's fields of the two tables which make the m2m relationship of this way:

My question is:

How to can I make that in my Movement model I can access to the corporal_segment_associated field that I want call in the __str__ method?

Any orientation is very useful :)


回答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:

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.



来源:https://stackoverflow.com/questions/39729238/manytomany-relationships-returning-fields-in-def-str-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!