mrlonely
mrlonely

Reputation: 25

How to retrieve data from manytomany table in python django based on its ID

Suppose there are two tables

  1. mysql table name : user, Django model name: User
  2. mysql table video : user, Django model name: Video

User model contain one field as

videos = models.ManyToManyField(Video, blank=True, null=True, related_name='video')

Now i have a new mysql table name: user_videos

+-------------------+---------+------+-----+---------+----------------+
| Field             | Type    | Null | Key | Default | Extra          |
+-------------------+---------+------+-----+---------+----------------+
| id                | int(11) | NO   | PRI | NULL    | auto_increment |
| user_id           | int(11) | NO   | MUL | NULL    |                |
| video_id          | int(11) | NO   | MUL | NULL    |                |
+-------------------+---------+------+-----+---------+----------------+

now i need to retrieve data my django like this mysql query: select * from user_videos order by id desc;

user.videos.all() is giving me order by video.id not user_videos.id

Any good approach to do this by using models in python django without using a raw query.

Upvotes: 0

Views: 3397

Answers (1)

fabio.sussetto
fabio.sussetto

Reputation: 7055

You can access the join table that Django automatically creates for you by doing:

User.videos.through.objects.all()

If you need to add more data to your join table, you can set up a many-to-many relationship with the through option and specify a custom model:

https://docs.djangoproject.com/en/1.11/topics/db/models/#extra-fields-on-many-to-many-relationships

Upvotes: 2

Related Questions