arcee123
arcee123

Reputation: 211

how to show data from joined tables in DJANGO DRF

I'm trying to show data from a table that has several ForeignKey fields assigned to it:

class Promotion (models.Model):
    User = models.ForeignKey(User)
    Rating = models.ForeignKey(Rating)
    Date_Effective = models.DateField()

    def __str__(self):
        return self.Rating.Rank.Short_Rank + ' ' + self.User.last_name + ' (' + str(self.Date_Effective) + ')'

class Rating (models.Model):
    Rank = models.ForeignKey(Rank)
    Genre = models.ForeignKey(Genre)
    Branch = models.ForeignKey(Branch)
    Image = models.FileField(upload_to='ranks')

    def __str__(self):
        return self.Rank.Display_Rank + " (" + self.Branch.Branch + "; " + self.Genre.Short_Term + ")"

I'm trying to build a serializer that shows the Rating.str value from it and User information.

class PromotionSerializer(serializers.HyperlinkedModelSerializer):
    Rating = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    users = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Promotion
        fields = ('Date_Effective', 'Rating', 'users')

This results in error:

Exception Type: TypeError at /member/api/promotions/
Exception Value: 'Rating' object is not iterable

I'm trying to figure this thing out. How do I do this? Thanks much.

Upvotes: 0

Views: 85

Answers (1)

ChidG
ChidG

Reputation: 3223

You are asking Django Rest Framework to return the primary key of the related object in PromotionSerializer by using PrimaryKeyRelatedField.

If you want it to return the unicode representation of the object, try using StringRelatedField instead: http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield.

In addition, as one of your comments mentions, you should not use many=True (no need to set it to false, just remove the argument).

Note: It's unconventional to use Title Case when naming attributes of classes in Python. Title case is normally reserved for class names themselves.

Upvotes: 1

Related Questions