[Fixed]-What is the right way to hard-code some methods and fields of particular instances of a model in Django?

1👍

Since Feed is a models.Model you can only assign model fields as class parameters. Assigning name = "Hacker News" won’t work on models. Since it doesn’t look like the shape of the data needs to change depending on the feed type, then just leave your model as-is, and implement your feed fetching based on the self.name attribute. Something like this:

# assumes a file called `feedfetcher.py` in the same 
# directory as your `models.py` file
from . import feedfetcher

class Feed(models.Model):
    name = models.CharField(max_length=75)
    rss = models.URLField(blank=True, null=True)

    def get_feed_data(self):
        return feedfetcher.fetch(self.name)


# feedfetcher.py

def fetch(name):
    if name == 'Hacker News':
        # get hacker news feed
    elif name == 'Reddit':
        # get reddit feed
    else:
        # we have no fetcher for this
        # kind of feed yet.
        raise ValueError('No fetcher for {}'.format(name))

If you add too many feeds this will quickly become unruly. I would probably split RSS feeds into a common method or class to make handling of those automatic. Add the following attribute to your model:

feed_type = models.CharField(choices=(('RSS', 'RSS'), ('API', 'API'))

And then you could check what the feed type is within get_feed_data and if it’s RSS, hand off to a specific RSS feed handler. I’m assuming each API will be different though, so you can keep the fetch method above to figure out and call each individual API.

0👍

I suggest inserting the fixed Feeds using fixtures and then make get_feed_data conditional based on name.

def get_feed_data(self):
    if self.name == "Hacker News":
        # Return data based on Hacker News API
    else:
        # return data based on self.rss
👤nima

Leave a comment