Skip to content

Instantly share code, notes, and snippets.

@Nolski
Last active May 8, 2017 19:55
Show Gist options
  • Save Nolski/23e4bb14fe23125c81f8cd2860741222 to your computer and use it in GitHub Desktop.
Save Nolski/23e4bb14fe23125c81f8cd2860741222 to your computer and use it in GitHub Desktop.
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)
# ...
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