添加更多与外键的关联

时间:2017-07-17 01:18:29

标签: django python-3.x django-models foreign-keys

我有两个模型:QuestionUserEdus

UserEdus可以对Question投票。

投票后,Question会存储已投票的相关UserEdus列表。我不知道如何创建和添加此关联。

Question可以有多少UserEdus正确的方法来考虑这个问题吗?

这是我到目前为止所拥有的。

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.ForeignKey(Question, null=True)

点击upvote按钮后会调用此视图,

def upvote(request,pk):
question = get_object_or_404(Question, pk=pk)
question.points += 1
request.user.useredus.votes_set.add(question)
question.save()

这将返回错误'UserEdus' object has no attribute 'votes_set'

我做错了什么?文档遵循这种模式。

2 个答案:

答案 0 :(得分:1)

request.user.useredus.votes = question 

这是正确的方法

答案 1 :(得分:1)

我认为你要找的是related_name参数和ManyToManyField模型字段。我会改变:

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

要:

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

这样你可以像这样进行查询:

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

您的代码如下:

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")

您的upvoteview看起来像:

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()

我希望有所帮助!