Reputation: 25
Suppose there are two tables
- mysql table name : user, Django model name: User
- 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
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