2

I have the following entities:

  1. Videos
  2. Tags
  3. Relationship entity - VideoTags

Here's the schema:

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)
    class Meta:
        db_table = u'tags'

class Video(models.Model):
    guid = models.CharField(max_length=36, primary_key=True)
    title = models.CharField(max_length=600)
    tags = models.ManyToManyField(Tag, through='VideoTag')
    class Meta:
        db_table = u'videos'

class VideoTag(models.Model):
    guid = models.CharField(max_length=36, primary_key=True)
    tag = models.ForeignKey(Tag)
    video = models.ForeignKey(Video)
    weight = models.FloatField()
    class Meta:
        db_table = u'video_tags'

Now, this all works well when creating the entities. Now say I want to pull video by its Id and iterate over its tags.

When I do:

video = Video.objects.get(pk=1)
tags = video.tags.all()

I get in fact a list of Tag entities as they are related to the video and not the relationship entity VideoTag. I would like to access the video's tags and more importantly one of the extra fields on the relationship table - weight. I cannot do that since the tags property on video is of type Tag.

Thanks :)

Yuval Kalev
  • 111
  • 6

1 Answers1

0

In the Django documentation says

If you need to access a membership's information you may do so by directly querying the Membership model:

It also says

Another way to access the same information is by querying the many-to-many reverse relationship from a Person object:

So you have to options, something like:

VideoTag.objects.filter(video=video).order_by('weight')

Or maybe

Tag.videotag_set.all().order_by('weight')
esauro
  • 1,276
  • 10
  • 17