[Answer]-Accessing a full object through a relation in Django

1👍

Thanks to this blog post I was able to implement this using ManyToManyField as suggested. I must say this blog post is better than any docs I found on the Django site itself.

MODEL:

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')
    prereqs = models.ManyToManyField(
        'self', through='Prereq', symmetrical=False, related_name='prerequired')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    def __unicode__(self):
        return self.title

class Prereq(models.Model):
    resource = models.ForeignKey(Resource, null=True, related_name='main_resource')
    prereq = models.ForeignKey(Resource, null=True, related_name='prereq_resource')

ADMIN:

from django.contrib import admin
from idhhb.models import Resource, Prereq

class PrereqInline(admin.TabularInline):
    model = Prereq
    fk_name = 'resource'
    extra = 5

class ResourceAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': 'title shortcode img summary url pub_date'.split() }),
    ]
    inlines = [PrereqInline,]


admin.site.register(Resource, ResourceAdmin)

TEMPLATE:

{% for prereq in resource.prereqs.all %}
    <li>{{ prereq.id }}</li>
{% endfor %}

0👍

prereq_backlink and prereq_resource are managers so access to the Resource will look like:

r = Resource.objects.get(id=2)
for prereq in r.prereq_backlink.all():
    print prereq.resource.title

But I join to @daniel-roseman’s question: why you didn’t use the ManyToManyField for this task?

class Resource(models.Model):
    ...
    prereqs = models.ManyToManyField('self')

Leave a comment