Last active
May 8, 2017 19:55
-
-
Save Nolski/23e4bb14fe23125c81f8cd2860741222 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Channel(MPTTModel): | |
# ... | |
tags = models.ManyToManyField('tags.Tag', blank=True, through='RankedChannelTag', related_name='ranked_tags') | |
# ... | |
class RankedChannelTag(models.Model): | |
channel = models.ForeignKey(Channel, on_delete=models.CASCADE) | |
tag = models.ForeignKey('tags.Tag', on_delete=models.CASCADE) | |
rank = models.SmallIntegerField(default=0) | |
# ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RankedTagSerializer(serializers.ModelSerializer): | |
rank = serializers.IntegerField(required=False) | |
tag = serializers.CharField(source='tag.name') | |
class Meta: | |
model = RankedChannelTag | |
fields = ('id', 'channel', 'tag', 'rank') | |
read_only_fields = ('id',) | |
class ChannelSerializer(serializers.ModelSerializer): | |
tags = RankedTagSerializer(source="rankedchanneltag_set", many=True, read_only=True) | |
# ... | |
# Serializing a channel throws: | |
# AttributeError: 'ManyRelatedManager' object has no attribute 'pk' | |
# Serializing a RankedTag works just fine. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment