1
Class NickName(models.Model):
    name = models.CharField()

    def __unicode__(self):
        return unicode(self.name)

Class Bob(models.Model):

    bob_nickname = models.ManyToManyField(NickName)

    def __unicode__(self):
        return unicode(self.bob_nickname)

Number1. How would I get the __unicode__ for class Bob to display the actual FK name, rather than the <django.db.models.fields.related.ManyRelatedFieldsManager Object at 0Xdsfjk>?

EDIT: simply doing self.bob_nickname.all() seems to work fine. It aint pretty, but it displays the info: [<NickName: Ron>,<NickName: Randy>]

Number2. Also, how can I get the def __unicode__ to not escape \n? I'd like to create a multiline unicode string

Thank you!

InfinteScroll
  • 664
  • 3
  • 11
  • 24
  • As you've found, `Model.manyToManyField` reveals a manager, not instances, so that you can do fancy things like filtering results before making the database query If you want to access objects, sure, iterate over the related objects and construct the string you want. Do note, you will want to look into `prefetch_related` as you will be doing a DB query per unicode call (printing 100 results will cause 101 queries) – Yuji 'Tomita' Tomita Mar 10 '14 at 05:38
  • In terms of your escaping issue, have a look at this question: http://stackoverflow.com/questions/267436/how-do-i-treat-an-ascii-string-as-unicode-and-unescape-the-escaped-characters-in?rq=1 – Dr.Elch Mar 11 '14 at 13:06

1 Answers1

1

Why don't you use values_list to get all related nick_names as list?

class Bob(models.Model):
    bob_nickname = models.ManyToManyField(NickName)

    def __unicode__(self):
        return u'\n'.join(self.bob_nickname.values_list('name', flat=True))
A. Grinenko
  • 341
  • 1
  • 3
  • 5