Django从另一个模型获取模型 [英] Django getting a model from another model
本文介绍了Django从另一个模型获取模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型,一个作者和一个文章.每篇文章都需要引用其作者,以便我可以在模板中访问其值.最有效的方法是什么?
I have two models, a Author and a Article. Each Article is needs to refer back to its Author so I can access its values in my template. What is the most efficient way of doing this?
class Author(models.Model):
name = models.CharField(max_length=256)
picture = models.CharField(max_length=256)
class Article(models.Model):
title = models.CharField(max_length=256)
author = #The Author model that wrote this article
date = models.DateTimeField(default=datetime.now)
body = models.TextField()
推荐答案
您需要使用Foreign Key
概念.以下是其实现:
You need to use the Foreign Key
concept for it. The following is its implementation:
class Author(models.Model):
name = models.CharField(max_length=256)
picture = models.CharField(max_length=256)
class Article(models.Model):
title = models.CharField(max_length=256)
author = models.ForeignKey(Author)
date = models.DateTimeField(default=datetime.now)
body = models.TextField()
保存时,您需要在views.py
中执行以下操作:
While saving it, you need to do the following in your views.py
:
if form.is_valid():
author = Author.objects.get(name="author name")
form.save(author=author)
希望有帮助...
这篇关于Django从另一个模型获取模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文