Cannot get object from queryset
Code below should substitute all \[\[(.+)\]\]
matches in 'content' field of AD with src of ADResource where (.+)
is alias
[[Similac]]
→ media/banners/2011/07/24/ad1.gif
[[res]]
→ media/banners/2011/07/24/ad2.png
It catches DoesNotExist exception on [[res]] or [[Similac]] and returns 'res' or 'Similac' strings.
开发者_Go百科ADResource table contents:
id alias src
----------------------------------------------------
1 Similac media/banners/2011/07/24/ad1.gif
2 res media/banners/2011/07/24/ad2.png
class ADResource(models.Model):
alias = models.CharField(max_length=256)
src = models.FileField(upload_to="media/banners/%Y/%m/%d/")
class AD(models.Model):
content = models.CharField(max_length=10000)
def getResourceURL(object, object_alias):
try:
return ADResource.objects.all().get(alias="%s" % object_alias).src.url
except ADResource.DoesNotExist:
return object_alias
def save(self, **kwargs):
self.content = re.sub(r'\[\[(.+)\]\]', AD.getResourceURL(self, r'\1'), self.content)
super(AD, self).save(**kwargs)
But this code is working and i get url of src field:
return ADResource.objects.all().get(alias='res').src.url
Oh, stupid question, i'm getting not a string but regex object and my match was in first subgroup.
self.content = re.sub(r'\[\[(.+)\]\]', lambda m: ADResource.objects.all().get(alias=m.group(1)).src.url, self.content)
精彩评论