[英]Django getting a model from another model
我有两个模型,一个作者和一个文章。 每篇文章都需要引用其作者,以便我可以在模板中访问其值。 最有效的方法是什么?
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
概念。 以下是其实现:
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
执行以下操作:
if form.is_valid():
author = Author.objects.get(name="author name")
form.save(author=author)
希望能帮助到你...
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, on_delete=models.CASCADE)
date = models.DateTimeField(default=datetime.now)
body = models.TextField()
>>> r1 = Author(name='John',picture='johnpicture')
>>> r1.save()
>>> r2 = Author(name='John',picture='paulpicture')
>>> r2.save()
>>> from datetime import date
>>> a = Article(title="Article1", body="This is a test",date=date(2017, 7, 27), author=r1)
>>> a.save()
>>> a.reporter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.