[Answered ]-Adding more associations with foreign key

1πŸ‘

βœ…

I think what you are looking for is the related_name argument and a ManyToManyField model field. I would change:

votes = models.ForeignKey(Question, null=True)

To:

votes = models.ManyToManyField("Question", related_name="votes")

That way you can do a query like so:

somevar = Question.objects.get(pk=1)
all_votes = somevar.votes.all()

Your code would look like:

class Question(models.Model):
    title = models.CharField(max_length=500, null=False)
    content = models.TextField(max_length=10000, null=False)
    author = models.ForeignKey('UserEdus', null=False)
    solution_found = models.BooleanField(default=False, null=False)
    points = models.IntegerField(default=1, null=False)
    post_date = models.DateField(default=date.today)

class UserEdus(models.Model):
    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
    bio = models.TextField(max_length=400, help_text="Enter your bio details here.")
    votes = models.ManyToManyField(Question, related_name="votes")

Your upvoteview would look like:

def upvote(request,pk):
    question = get_object_or_404(Question, pk=pk)
    question.points += 1
    question.save()
    useredus = UserEdus.objects.get(user__username=request.user.username)
    useredus.votes.add(question)
    useredus.save()

I hope that helps!

πŸ‘€Chris Jones

1πŸ‘

request.user.useredus.votes = question 

That’s the correct way

Leave a comment