我試圖對學習資源(書籍,DVD等)進行建模,以及這些資源具有哪些先決條件。通過Django中的關係訪問完整對象
先決條件也是一種資源。所以我的問題是,什麼Django 建模技術最好地捕捉這種關係?這項研究的資源是 簡單:
from django.db import models
from django.utils import timezone
class Resource(models.Model):
title = models.CharField(max_length=300)
shortcode = models.CharField(max_length=20, null=True, blank=True)
img = models.URLField(null=True, blank=True)
summary = models.TextField(null=True, blank=True)
url = models.URLField('Link to Resource', null=True, blank=True)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __unicode__(self):
return self.title
但是,我不知道什麼是「最好」的方式向 前提下,給定的模型,它是一個Resource
也是最重要的是有可變數量的先決條件(從而消除了簡單地擁有自我指涉的父母的可能性)。這是我目前的做法:
class Prereq(models.Model):
prereq = models.ForeignKey(Resource, null=True, related_name='prereq_backlink')
resource = models.ForeignKey(Resource, null=True, related_name='prereq_resource')
def __unicode__(self):
return self.resource.title
這種方法的問題是訪問的先決條件並 沒有給我一個完整的資源對象的工作,所以我不能訪問 的各個領域(標題,簡碼,等):
[email protected]:~/domains/org/metaperl/tmp/idhhb/django/mysite$ ./manage.py shell
>>> from idhhb.models import Resource, Prereq
from idhhb.models import Resource, Prereq
>>> p = Resource.objects.get(id=2)
>>> p.title
u'American Book of the Dead'
>>> r = Resource.objects.get(id=2)
r = Resource.objects.get(id=2)
>>> p1 = r.prereq_backlink
>>> p2 = r.prereq_resource
>>> p1
<django.db.models.fields.related.RelatedManager object at 0x2e279d0>
>>> p2
<django.db.models.fields.related.RelatedManager object at 0x2e27a90>
>>> p1.title
p1.title
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'RelatedManager' object has no attribute 'title'
>>> p2.title
p2.title
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'RelatedManager' object has no attribute 'title'
>>>
爲什麼不直接使用一個自我指涉的關係?如果某個資源具有「父」fk,那麼這是您的先決條件 – Brandon 2015-03-13 18:42:12
因爲先決條件的數量是可變的,理想情況下限制爲5,但該要求可以放寬。但是,肯定不是隻有一個先決條件。 – 2015-03-13 21:42:35
好吧,爲什麼不能自我參照多對多的關係呢? – 2015-03-13 21:48:09