Django getting a model from another model

2019-06-13 22:23发布

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()

2条回答
走好不送
2楼-- · 2019-06-13 23:12
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
查看更多
Animai°情兽
3楼-- · 2019-06-13 23:25

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()

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)

Hope it helps...

查看更多
登录 后发表回答