Reputation: 1169
I have a custom field that has an image field as a reference, i use my field as below:
poster = ImageField(upload_to=get_path, null=True, blank=True )
cropping = CropField('poster')#this is my custom field
Now i need a way to listen referenced image field changes... I think i can use signals in models.py but i need a dry way. I do not want to place a signal for every model that has cropping custom field.
I think i need a way to do it in custom field code. But where? in FieldDescriptor? in FieldCreator?
Upvotes: 1
Views: 192
Reputation: 2143
If you want to determine whether an underlying property of a model has changed, you can overwrite the save method to do the check. This answer describes how you can do that.
To make it available to any model that has a CropField
, you can create an abstract base class for your models that use CropField
class CropFieldModel(models.Model):
def save(self, *args, **kwargs):
#logic to determine which field is an imageField.
attrs = dir(self)
for attr in attrs:
if isisntance(attr, CropField):
#whatever logic you want to to modify the object
super(CropFieldModel, self).save(*args, **kw)
class Meta:
abstract = True
Then all your models that use CropField
you can just subclass CropFieldModel
and you will get the custom save function.
class MyModel(CropFieldModel):
poster = ImageField(upload_to=get_path, null=True, blank=True )
cropping = CropField('poster')
This will allow you to not have to repeat yourself and provide you custom logic whenever a model instance changes. You can also use getattr
to invoke a function defined in your subclass if you want each model to have different behavior when it's changed. I'm not for sure what you are trying to accomplish with your custom field but hopefully this points you in the right direction in creating your custom model and fields.
Upvotes: 1