问题
I am trying to create a user sign up form in Django that allows for a primary field with an associated integer field. I need each user to be able to select a genre (for movies), and then the percentage (0-100) they like that genre. I have created the percentage as a separate model, but I need it to be associated with each genre per user. How can I associate each user's genres with a specific "like" percentage? Right now, I just have a box of the genre list, with no way to select the percentage like for each genre.
#app/models.py
class Length(models.Model):
length = models.IntegerField(default="Default")
def __str__(self):
return str(self.length)
class Genre(models.Model):
title = models.CharField(max_length=40, help_text="Enter genre name", default="Default")
like = models.ManyToManyField(Like, help_text='Genre like percent', default="1")
def __str__(self):
return self.title
#users/models.py
import stuff
class User(AbstractUser):
first_name = models.CharField(max_length = 30, blank = True)
last_name = models.CharField(max_length = 30, blank = True)
email = models.EmailField(unique = True)
city = models.CharField(max_length = 30, blank = True, default='Default Town')
state = models.CharField(max_length = 2, default='CA')
summary = models.CharField(max_length=250, default='Default summary')
genres = models.ManyToManyField(Genre, help_text='Select each genre.', default='default', related_name='genre_model')
def __str__(self):
return self.email
#users/forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = User
fields = ['username',
'email',
'first_name',
'last_name',
'city',
'state',
'summary',
'genres',]
回答1:
A good way to do this could be to use a through model linking the user with the genre, keeping track of how much the user likes that genre within that model instead of within the Genre model since the "like" percent depends on the connection with the user.
So you could have a class that looks something like:
class Like(models.Model): # name this model something better than "Like"
user = models.ForeignKey(User, related_name="liked_genres")
genre = models.ForeignKey(Genre, related_name="user_ratings")
rating = models.IntegerField()
This will also mean that a user can like several genres instead of having just one.
来源:https://stackoverflow.com/questions/53755518/django-model-field-with-secondary-field