[Answered ]-One to Many relationship of models in Django

2👍

✅

You need to use ManyToMany relationship here. One user can watch many videos. And one video can be watched by many users.

Here’s an example model structure where you can store more MetaData about the videos the user watched.

class User(models.Model):
    name = models.CharField(max_length=40)
    videos_watched = models.ManyToManyField('Video', through='WatchedVideo')


class Video(models.Model):
    name = models.CharField(max_length=40)
    time  = models.IntegerField()


class WatchedVideo(models.Model):
    user = models.ForeignKey(User)
    video = models.ForeignKey(Video)
    watched_on = models.DateTimeField(auto_now_add=True)

To WatchedVideo inline inside tha UserAdmin, try this:

#admin.py inside your graph app
class WatchedVideoInline(admin.TabularInline):
    model = WatchedVideo

class UserAdmin(admin.ModelAdmin):
    inlines = [WatchedVideoInline]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Leave a comment