Outputing JSON for a model with properties and db fields in Wagtail/Django

I thought I’d share this example because it took me ages to figure out how to output JSON for a model which included a model property as well as the actual fields of the model. For our footer links we had a property called ‘link’ in the snippet which would return either a full URL or a relative link to a Wagtail CMS page. If we just tried to return link_page directly without the link property we’d just get the ID of the page, this wouldn’t be any use to us in the JSON.

This example uses a comprehension list to get the model property and model fields together.
In the models.py for the footer snippet:


class MainFooterLink(models.Model):

 link_title = models.CharField(max_length=255)
 link_url = models.URLField("Link URL", blank=True)
 link_page = models.ForeignKey(
 'wagtailcore.Page',
 null=True,
 blank=True,
 related_name='+'
 )
 order_rank = models.IntegerField(default=1)

 panels = [
 FieldPanel('link_title'),
 FieldPanel('link_url'),
 PageChooserPanel('link_page'),
 FieldPanel('order_rank'),
 ]

 def __unicode__(self):
 return self.link_title

 @property
 def link(self):
 if self.link_page:
 return "<your base URL here>" + self.link_page.url
 else:
 return self.link_url

register_snippet(MainFooterLink)

Define your view function (make sure to import json and HttpResponse):

def footer_json(request):

footerlinks = MainFooterLink.objects.all().order_by('order_rank')

the_linksĀ = []
the_linksĀ = [{'title':s.link_title, 'link':s.link , 'order':s.order_rank} for s in footerlinks]

return HttpResponse(json.dumps(the_links, sort_keys=True, indent=4, separators=(',', ': ')), mimetype='application/json')

Advertisements