I've got a class like this:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
and another class like this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image)
what i'd like to do with that class is this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image, sizes=((90,90), (150, 120)))
where i'm can specify the sizes that i want the Image class to use to resize itself as a argument rather than being hard coded on the class. I realise 开发者_如何学GoI could pass these in when calling resize_image if that was called directly but the idea is that the resize_image method is called automatically when the object is persisted to the db.
if I try to pass arguments through the foreign key declaration like this i get an error straight away. is there an easy / better way to do this before I begin hacking down into django?
You might be pushing it uphill; it's uncommon to try and apply arguments to FK's.
The conventional solution to your specifics is to use a thumbnailer (like "sorl") to do a thumbnail substitution immediately before delivery - ie: in the template eg:
{% thumbnail myobj.image 500 500 %}
Although personally I have added routines into my classes to make it easier to access those thumbnails. eg:
def thumbnail(self):
path = # work out the path to the thumbnail
try:
#access the path where I expect the thumbnail file to be
except #failure:
# generate the thumbnail using the dimensions specified by the class
return #path to the thumbnail
All the attributes of an object in Django are stored in the database, so you are going to have to make your sizes a Field in your model. You can't just set random properties and expect them to persist.
As there isn't a field for a list of tuples you are going to either have to kludge it by using a text field or write a ListOfTuplesField or better still an ImageSizesField that inherits from a ListOfTuplesField. You'd have to write code to serialize it to the database (converting to text would probably be the easiest way) and also to parse it back, or there may be a JSONField type somewhere.
So now your SomeClassWithAnImage model has a ForeignKey to the Image, and an ImageSizesField. When it gets saved your overriden save() method then calls the Image's resize method with the values from the ImageSizesField.
What happens if another SomeClassWithAnImage points to the same Image though?
精彩评论