[英]xDjango Inner Join tables with queryset
我正在尝试INNER加入2个表格: Comments
和Auth
。 因此,我将userid
存储在Comments
表中,并且需要将其与Auth
配对。
我使用过.raw()
,但是我不想使用raw()
,我也尝试了其他类似get_objects_or_404
类的get_objects_or_404
但是由于多个查询而无法正常工作。
这是我的查询,例外。
SELECT * FROM index_comment INNER JOIN auth_user WHERE index_comment.userid=auth_user.id
这是我的评论模型:
class Comment(models.Model):
content = models.TextField()
userid = models.IntegerField()
published = models.DateField(default=timezone.now)
postid = models.IntegerField()
Views.py
def readPost(request, postName):
content = get_object_or_404(Post, link=postName)
kategori = get_object_or_404(Category, id=content.category_id)
user = get_object_or_404(User, id=content.username_id)
if request.method == "POST":
form = sendComment(request.POST)
if form.is_valid:
formContent = strip_tags(request.POST["content"])
newComment = Comment()
newComment.content = formContent
newComment.postid = content.id
newComment.save()
return redirect('post',content.link)
else:
form = sendComment
args = {
"content": content,
"kategori": kategori,
"user":user,
"commentForm": form,
}
# return HttpResponse("cat.id")
return render(request, "theme/single.html", args)
这是forms.py
class sendComment(forms.Form):
content = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
因此,我需要将Comments
表中的userid
与身份Auth
ID配对,然后获取username
。
通过使用从index_comment.userid到auth_user.id的外键关系( django docs )正确设置模型,Django将为您处理联接并通过主模型(index_comment)使联接表(auth_user)的列可用。
就像是:
from django.db import models
from django.contrib.auth.models import User
class Comment(models.Model):
content = models.TextField()
userid = models.ForeignKey(User,on_delete=models.CASCADE)
published = models.DateField(default=timezone.now)
postid = models.IntegerField()
会将注释表中的用户标识与django内置的auth功能的用户表绑定。 名称字段将可用于评论,例如
comment.userid.username
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.