I'm currently working on a CS project that works similar to kickstarter, which the user can back their projects. I already had a follow function which allows the user to follow their favorite projects, the model is shown below:
class Team(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='team')
following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
There is a function in my view.py that adds the user to the MANYTOMANY field if the user clicks 'follow' button.
My question is how should my 'back' model be structured? I need to store the amount the user backed this project, or 'team' in this case, and date they backed. Create a model for 'follow' function wasn't that hard because I didn't need to store any additional data other than just User. But for 'BACK' function, I need to store some additional data like 'date backed', 'amount backed'.
You can use a ManyToManyField
with through
In your case, it would be something like this:
class Team(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='team')
following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
backers = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Backer', related_name='backers', blank=True)
class Backer(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
team = models.ForeignKey('Team', related_name='team')
amount = models.FloatField()
date_joined = models.DateField()
and then to add backers:
backer = Backer(user=some_user, team=some_team, date_joined=date(2017, 02, 22), amount=200)
and you can get the backers on Team through the ManyToManyField
:
SomeTeam.backers.all()
>>> <QuerySet [<User: Some User>]>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.