Reputation: 27
im new to django and was trying to create models for a youtube like website. im trying to create models such that a user has record of:
1) playlists he has uploaded.
2) playlists he has viewed. i tried the following models:
class User(models.Model):
name=models.CharField
email=models.EmailField
password=models.CharField
isTeacher=models.BooleanField
upvotes=models.IntegerField
class Playlists(models.Model):
creator=models.ForeignKey(User, on_delete=models.CASCADE)
viewed_by=models.ManyToManyField(User, on_delete=models.CASCADE)
name=models.CharField
size=models.IntegerField
i hope you get what i want to do. obvoiusly this scheme doesn't work. but i want to do something on similar grounds
Upvotes: 0
Views: 63
Reputation: 477684
That can work, but you need to specify different values for the related_name=…
parameter [Django-doc], this is the name of the relation in reverse, so you can construct such model with:
from django.conf import settings
class Playlists(models.Model):
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='created_playlists'
)
viewed_by = models.ManyToManyField(
settings.AUTH_USER_MODEL,
related_name='viewed_playlists'
)
name = models.CharField(max_length=128)
size = models.IntegerField()
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Upvotes: 1