我能';t使Django正确内部连接:(
尽管已经到处寻找类似的问题,但我仍然无法使用Django ORM的内部连接使查询工作……如果这听起来很愚蠢,很抱歉,但这是我第一次在项目中使用Django,尤其是ORM 我有一个Articles表和一个Users表(在我的例子中命名为Fellows),Articles表在author上有它的外键,并引用Fellows表中的用户id我能';t使Django正确内部连接:(,django,vue.js,inner-join,Django,Vue.js,Inner Join,尽管已经到处寻找类似的问题,但我仍然无法使用Django ORM的内部连接使查询工作……如果这听起来很愚蠢,很抱歉,但这是我第一次在项目中使用Django,尤其是ORM 我有一个Articles表和一个Users表(在我的例子中命名为Fellows),Articles表在author上有它的外键,并引用Fellows表中的用户id class Fellow(models.Model): id = models.AutoField(db_column='ID', primary_key=T
class Fellow(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # ID
user_id = models.PositiveBigIntegerField(db_column='User_ID', unique=True) # Global User ID.
nickname = models.CharField(db_column='Name', max_length=64, db_collation='utf8mb4_general_ci') # Display Name
user_password = models.CharField(db_column='User_Password', max_length=256, blank=True, null=True) # Passwd
gold = models.IntegerField(db_column='Gold') # Credits
faction = models.ForeignKey('Faction', models.RESTRICT, db_column='Faction', default=1) # ID Faction
class Meta:
managed = False
db_table = 'Fellows'
def __str__(self):
return self.nickname # Test.
class Article(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # ID
author = models.ForeignKey('Fellow', models.CASCADE, db_column='ID_User', default=1) # Global User ID
title = models.CharField(db_column='Title', max_length=32) # Title
content = models.TextField(db_column='Content') # Content
posted = models.DateTimeField(db_column='Posted') # Date Posted
source = models.CharField(db_column='Source', max_length=64, blank=True, null=True) # Source picture url of the article.
class Meta:
db_table = 'Articles'
我试图获得发表文章的相关作者的显示名,但没有成功
这是my views.py:
from .models import Article
def index(request):
"""
And then Vue.JS will take care of the rest.
"""
# articles = Article.objects.order_by('-posted')[:5] # Returns everything inside Articles table but nothing inside Fellows table.
# articles = Article.objects.select_related() # No Result.
# Still can't get display_name in index.html with this one.
articles = Article.objects.raw('SELECT Fellows.Name AS Display_Name, Articles.ID, Articles.Title, Articles.Content, Articles.Posted, Articles.Source FROM Articles INNER JOIN Fellows ON Fellows.User_ID = Articles.ID_User ORDER BY Articles.ID DESC LIMIT 5;')
data = {
'articles': articles,
}
return render(request, 'home/index.html', data)
原始请求仅使用sql解释器返回一切正常,因此有两个选项:
const store=新的Vuex.store({
声明:{
文章:[
{文章%中的文章为%s}
{
标题:“{article.title}}”,
内容:“{article.content | linebreaksbr}}”,
来源:“{%static'home/img/'%}”+'{{article.source}}',
display_name:'{{article.display_name}}',//也许这不是检索display_name的方法?
},
{%endfor%}
],
},
});
//组成部分。
ArticleList=Vue.component('article-list'{
数据:函数(){return{articles:store.state.articles},
模板:“#文章列表模板”,
});
ArticleItem=Vue.component('article-item'{
分隔符:['[',']]'],
道具:['id','title','content','source','display_name'],
模板:“#文章项目模板”,
});
...
如果有人能帮我,我将不胜感激!问题解决了
我必须更改外键约束Articles.ID\u用户,该用户现在指向Fellows.ID
以前,该约束导致Fellows.User\u ID
我最终可以使用:
articles = Article.objects.select_related('author').order_by('-posted')[:5]
事实上,最终通过article.author在前面访问它,就这么简单
但是我仍然不明白为什么原始sql查询(使用mysql解释器)和内部连接在引用Fellows.User_ID时运行良好,而ORM中显然不是这样
尽管我的sql relational运行正常,但它可能是错误的或不理想的,因此我仍然愿意接受建议!
Article.objects.select_related('author').all()
和{{Article.author.昵称}
在模板中应该可以工作。你必须引用字段名,而不是数据库列名。在你的回复中,我尝试了你建议的方法,但是它返回了一个空列表。我已经使用其他型号的应用程序测试了外键,但这次使用了一个简单的模板(没有vuejs),并按预期工作。这次我将尝试使用具有相同表格的虚拟应用程序,以找出问题所在!x_xPlease in code questions给出一个--cut&paste&runnable代码,包括作为代码的最小代表性示例输入;所需和实际输出(包括逐字错误消息);标记和版本;清晰的规范和解释。提供最少的代码,即显示为OK的代码,扩展为显示为不OK的代码。(调试基础。)对于包含DBMS和DDL(包括约束和索引)的SQL输入格式为表的代码(&input)。停止尝试对总体目标进行编码,并解释您对给定代码的期望以及原因。约束不需要保留、声明或在SQL中查询。(但如果它们保留,则某些表达式返回的结果与您本可以使用的其他表达式相同,否则不会。)ORM使用FKs来让您编写特定的OO代码,并将其映射到SQL;它可能会生成只有在FKs有效时才正确的查询,但它不需要(或者可能需要更少的处理,但DBMS使用约束来最小化SQL代码的计算)练习:了解ORM声明创建的表并将查询OO代码与不依赖约束的最简单等效SQL进行比较。不需要查询约束的原因是,在关系模型中,每个查询表达式及其表值表示一个关系(ship)/关联以及满足它的行;查询构建一个关系(ship)/关联及其来自基表关系(ship)s/associations&rows的行。FK由于关系模型和ER模型的错误表述而被普遍错误地称为“关系”;它们和其他约束总是DBMS用于禁止无效更新(&optimize)的正确语句。(ORM是不必要的、限制性的,只是提供了对模糊数据库的指针式访问。)感谢您的回复和解释!这是一大堆信息,我将在本周花时间深入了解它的工作原理,并在将来避免这种情况,祝您愉快!!:)
articles = Article.objects.select_related('author').order_by('-posted')[:5]