Reputation:
I have the following method I am trying to write:
class MTurk(models.Model):
...
def parse(self, url):
res = requests.get(url)
node = html.fromstring(res.content)
data = MTurk()._parse_page(node)
self.update(**data)
However, when I try and do self.update(**data)
it tells me:
AttributeError: 'MTurk' object has no attribute 'update'
Normally I would do MTurk.objects.filter(pk=self.pk).update(**data)
, but is there a way to do this from within the model method itself without having to re-call everything?
Upvotes: 0
Views: 545
Reputation: 3611
The update
function doesn't seem to be accessible from an individual object, but is rather used on a QuerySet.
It's however not a very Djangonic way of handling that kind of functionality, but you'd rather want to save the model outside the model, basically from the function/place that called parse
in the first place, basically like this:
# Fetch an object
mturk = MTurk.objects.get(id=1)
# Call the parse method
mturk.parse(my_url)
# Save the object
mturk.save()
You could however still call the save
function from within the model of course, in that case you'd just replace the update
function with a save
function, and you'd need to store the values to the model with self
.
The save
function also takes an argument update_fields=[]
in which you can specify which fields you want to save (and ignore the rest). This might be what you're looking for.
class MTurk(models.Model):
...
def parse(self, url):
res = requests.get(url)
node = html.fromstring(res.content)
data = MTurk()._parse_page(node)
self.data_1 = node # Store some data
self.data_2 = data # Store some more data
# Only save the given fields
self.save(update_fields=["data_1", "data_2])
Upvotes: 1