Search code examples
pythondjangoforeign-key-relationshippodcast

Accessing objects with a foreign key relationship in Django?


I'm currently trying to modify the django-podcast module so the podcast's xml file is statically served instead of being generated on every request for it.

I am attempting to rewrite the channel's xml file every time an episode is modified, created, or deleted and to do so I'm using django signals. What I would like to do is something like this...

from django.db.models.signals import post_save, post_delete
from django.template.loader import render_to_string

def update_xml_file(sender, **kwargs):
    f = open('channelrss.xml', 'w')
    f.write(render_to_string('podcast/show_feed.html', {'object': sender.show}))
    f.close()

class Show(models.Model):
    ...

class Episode(models.Model):
    post_save.connect(update_xml_file)
    post_delete.connect(update_xml_file)
    ...
    show = models.ForeignKey(Show)
    ...

The problem I keep running into is that sender.show is a ReverseSingleRelatedObjectDescriptor and not an actual instance of the Show class. I also tried reloading the sender object using sender.pk as the primary key value like this...

Episode.objects.filter(pk=sender.pk)

but apparently sender.pk returns a property object and not an integer or string and I don't know how to get it's value, so I guess I have two questions.

How can I retrieve the instance of Show associated with the Episode? and what the heck is a property object and why does sender.pk return it?

Thanks ahead of time for your response!

Josh


Solution

  • You can try:

    def update_xml_file(sender, instance=False, **kwargs):
        f = open('channelrss.xml', 'w')
        f.write(render_to_string('podcast/show_feed.html', {'object': instance.show}))
        f.close()
    

    when instance.show.name_field is name_field of the model.