user2781163
user2781163

Reputation: 169

Override model __init__ for an attribute which gets its value from running a method using another attribute as an argument

I'm new to Django and was wondering how I can change __init__ (I assume this is the right approach) so that when I add a new object, one of the attributes 'b' gets its value from a method that uses the value of the attribute 'a' as an argument.

For example:

I have a model Poll, which contains attributes question, and asked_online. Where asked_online uses the value of question to interact with the API of a web forum to check if its already been asked there and if so sets it to the value true

Edit:

Better Example.

A model 'Tag' which contains the attribute 'name' and 'num_post'. 'num_post' uses 'name' to look up the number of posts on stack overflow that contain that tag.

This is used as an initial value for the object where web app updates the value every so often on a weekly schedule(this is just giving context).

Upvotes: 1

Views: 123

Answers (1)

Rohan
Rohan

Reputation: 53316

Instead of changing the __init__() method, you can implement asked_online as property of the class.

Example:

class Poll(models.Model):
    #your fields

    @property
    def asked_online(self):
        #check if self.question is asked using some method
        return True # if asked online, else False

Upvotes: 2

Related Questions