[英]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.