-3

I have two models: Item and Photo. Item is foreignkey to Photo so one item can have many photos connected which is quite usual.

Item class:

class Item(models.Model):
name = models.CharField('Item Name',
    max_length = 150,
    null = False,
    blank = False
)
description = RichTextField('Item Description')

Photo class:

class Photo(models.Model):

path_and_rename = PathAndRename()

photo = models.ImageField(upload_to = path_and_rename, blank = True, null = True)
item = models.ForeignKey('Item', related_name = 'photo_set')

When I'm creating new Item entry with bunch of photos I'd like to do some additional stuff: launching asynchronous task for indexing and email notification of user - some_async_task(). I'm trying to do it by Item.save() method:

    def save(self):
    super(Item, self).save()

    some_async_task.delay(self.id)


@task(name="something")
def something(item_id):
    print Item.objects.get(pk=item_id).photo_set.first().photo.url

It seems save() method of Item model is exactly what I need but problem is that even after calling super() I can't get data about related Photo entries because such relationship doesn't exist.

What is the best way to run method after Item entry was created and all related Photo entries were related?

post_save signal doesn't fix situation.

Spark
  • 17
  • 4
Hazaard
  • 3
  • 4

1 Answers1

0

As Item is the main model and the photos are related, this means that when Item is saved it does not necessarily have the relations to the photos, yet.

To know when this has happened: "to run method after Item entry was created and all related Photo entries were related" is something that depends on your business logic.

Do you know in your view when exactly all of the photos have been added?

If yes: then call the task then and there, in your view code.

If no:

Risadinha
  • 16,058
  • 2
  • 88
  • 91
  • Thanks Risadinha. I was using `post_save` signal actually on `Item` object. Results were the same. So it seems that it's better to tweak `Photo.save()` method or bind `post_save` signal to `Photo` and run task with every photo update. Also I did put `sleep(10)` function at top of async task so at moment actual query is being passed to database all entries are updated and relations are saved. And it works. But I still don't like such approach. – Hazaard Feb 26 '16 at 12:54
  • After thinking a bit more (which is always neccessary :) it became clear that such logic should go only into view. Putting everything into model and chaining signals is bad idea. Only the view has full contol over flow of related models so everythong I need is just put call to my async tasks into view after `item.save()` code. – Hazaard Feb 27 '16 at 19:31