-
-
For a day or so now I’ve been battling with Django’s model inheritance, which has a particularly frustrating approach to dynamic polymorphism. The problem is that when one is implementing a group of related models using multi-table inheritance and you attempt to iterate over the bog standard QuerySet for the parent class, we see an unfortunate phenomenon: attributes and methods specific to a subclass will not be available as the list we are returned is a list of instances of the parent class, not the various children.
For example, I have a basic CMS which models a Page as having a series of Nuggets. A Nugget could be a simple TextNugget, a TwitterNugget, a BlogNugget etc. Each nugget has a title but beyond that each subclass must implement a method content() which returns the HTML content (including templatetags, in case you’re interested) which will be rendered by the browser in the appropriate place. For ease of use I wish for my users to be able to select from available Nuggets without worrying about their type.
class Nugget(models.Model): title_text = models.CharField(_('Title'), max_length=200) show_title = models.BooleanField(_('Show')) text = models.TextField(_('Text'), blank=True) def __unicode__(self): return self.title def title(self): return self.title_text def content(self): return self.text # extends Nugget class TwitterNugget(Nugget): username = models.CharField(_('username'), max_length=30) def __unicode__(self): return self.title def content(self): return "{% insert_tweets user" + self.username + "%}" def title(self): return self.title_text
In order to access, for example, the content method of a
Nugget
and be sure that we’re going to get the twittertemplatetag
, rather than the text which the inherited method would provide, we need to be sure that the iterator provided by theQuerySet
is going to give us instances of the child (TwitterNugget
) class, rather than instances ofNugget
. In order to achieve this, we should override theManager
for theNugget
class to return a new kind ofQuerySet
– one with overriden__getitem__
and__iter__
methods which cast our models to the correct child classes. In turn this requires us to implement this new type ofQuerySet
(thePolymorphicQuerySet
)Determining which type of object should be returned in the iterator is done using a
content_type
field in the model – we have to override thesave
method on theNugget
to make sure that the content_type is written when we persist the model.content_type
is aForeignKey
to theContentType
model provided in the djangoContentTypes
package.from django.contrib.contenttypes.models import ContentType from django.db.models.query import QuerySet class PolymorphicQuerySet(QuerySet): def __getitem__(self, k): result = super(PolymorphicQuerySet, self).__getitem__(k) if isinstance(result, models.Model) : return result.as_child_class() else : return result def __iter__(self): for item in super(PolymorphicQuerySet, self).__iter__(): yield item.as_child_class() class NuggetManager(models.Manager): def get_query_set(self): return PolymorphicQuerySet(self.model) class Nugget(models.Model): title_text = models.CharField(_('Title'), max_length=200) show_title = models.BooleanField(_('Show')) text = models.TextField(_('Text'), blank=True) content_type = models.ForeignKey(ContentType,editable=False,null=True) objects = NuggetManager() def save(self, *args, **kwargs): if(not self.content_type): self.content_type = ContentType.objects.get_for_model(self.__class__) super(Nugget, self).save(*args, **kwargs) def as_child_class(self): content_type = self.content_type model = content_type.model_class() if (model == Nugget): return self return model.objects.get(id=self.id) def __unicode__(self): return self.title def title(self): return self.title_text def content(self): return self.text # extends Nugget class TwitterNugget(Nugget): username = models.CharField(_('username'), max_length=30) objects = NuggetManager() def __unicode__(self): return self.title def content(self): return "{% insert_tweets user" + self.username + "%}" def title(self): return self.title_text
-
It is with great sadness that I inform you all that my Asus eeePC 701 has finally exhaled it’s last 7-inch breath, wheezing under the weight of the many superfluous processes running on it’s aging LinuxMint installation. Please join me in thanking it for many years of service – it really did punch well above it’s weight.
Of course we shouldn’t dwell – enter the Asus eeePC R101. One year on from the theft of the Gateway netbook I purchased in New York, this pocketable(-ish) wonder is riding on my back everywhere I go, allowing me to progress my pet projects in any downtime I might find. It is no deluxe model, in fact it is as basic as they come, but it’s now dual booting Ubuntu Netbook (with Unity interface) and Windows 7. I’ve been developing a client’s site (django) on it under the Ubuntu installation and it’s a joy to use. I guess one benefit of spending years with a 7-inch screen and underpowered Celeron processor is that the bar is set low for subsequent purchases…
-
This document was written as my submission for the computer science writing course I took in my third year of study at the University of York. It attempts to summarise the privacy issues associated with the development of new technologies in the information communications domain. Please don’t read with too much of a critical eye – it is old now and it was unfortunately a last minute effort, which I may one day improve.
Introduction
In order for one to consider the broad topic of ethics with regard to computer engineering, it is important to be sure that we understand precisely what “ethics” are. In her lecture notes, Susan Stepney defines ethics to be “right and wrong behaviour in a society” [1, p25], a definition expanded upon in Computer Ethics: “the code or set of principles by which people live” [2, p14]. These broad definitions suggest each of us have a good idea what is right and what is wrong, but a question central to the topic of this review is “can we judge the use of the Internet with existing ethical frameworks?” [1, p9]. (more…)
-
I thought getting a kitten would keep me company. I already have a cat who is still only young but old enough to want to sleep all day. The idea of the kitten was that our cat could have someone to play with while we were at work. Except that I was not at work owing to unexpected redundancy so voila! I had the time to look after and nurture a kitten whilst looking for jobs.
So here we are. Peanut and I. Or Winston and I. Or Winslow and I. Still not sure about the name. And whilst his prancing antics and lamb-like frolicking is a joy to watch, the constant attack on my hands as I type this, the incessant desire he has to chew on my laptop charger cable (instead of the perfectly good ball of wool I keep throwing at him) is getting rather trying. And it’s Day 1.
I expect the same is felt with children. You think about the way the little one will grab your finger in its tiny grip. The adoring look of complete trust and faith. The ‘I wuv you’ moments as they clamber up onto your lap. No one really mentions the inane whining or the constant demand for attention, as in not-for-one-second-can-you-get-a-tiny-moment-to-think. Or the deviousness of a five year old girl hitting her little brother around the head and then telling you, sweetly and genuinely concerned, that he fell over. The constant demand for attention. It is as if it is something that is shameful to be discussed, as if children were somehow exempt from the evil and bad nature of humans. As if they were some other form of life entirely and should only be praised. And for what? Being so small?
Not that I know this firsthand of course. Cats are not my replacement children as older women (and certain annoying contemporaries) love to tell me. I choose cats. They have just the right amount of dependency and cuteness that I crave. And they will do just fine until I can get a dog. No, it’s not my experience of children but my sister’s.
She looks fabulous at all times. She has three kids under five and still manages to maintain a toned, size 8 body, highlighted roots and a glowing complexion which astounds me every time. She has not slept in five years but I am the one who looks like I am suffering from domestic abuse: purple, swollen bags, translucent white skin, puckered forehead. ( I am also the one who looks like I’m still carrying baby weight. And I am ten years younger.) But despite her glamour, she is exhausted. She is drained and without patience or hope that this ongoing battle that she relives every day will ever end. I tell her it will get easier, that millions of mothers do it every day, that she is not alone. She looks at me like I am deluded. Frankly, it does not matter. When you feel like shit, knowing that other people are feeling like shit too is just annoying.
And she’s a stay-at-home mum with a wealthy husband. She has help. She has a cleaner. Most mothers can’t afford those luxuries and most can’t afford not to work. Can’t afford in the financial sense but also in the sense that their sanity is at risk if they stop working. The levels of exhaustion in those two scenarios literally blows my mind. I can’t help but conclude that having children is a penance, a sentence that has been socially accepted to be handed down to women, generation by generation. A constant reminder that Woman screwed up and ate the apple.
That’s why I’m sticking with cats. For now.
-
If you’re the guy who stole my laptop and contents of my laptop bag last night (18/5/10) please could I have my Moleskin notebook back? It has only sentimental value and I’ll even pay you to return it…
Thanks.
-
If like me you find yourself often frustrated and even drawn in by the frenzy of consumerism around you perhaps it would pay to let off a little steam and buy something. How about buying Nothing? It’s a neat little Amazon rip off from the folks over at dothegreenthing.com.
Seriously though, I am ashamed to say that I am quite the consumer. It pains me to see quite how easily the combination of advertising and media exposure manipulate my will and desires. In particular I find myself sold by product placement in movies – a really good movie draws you in, you lower your guard and just as the hero of the movie utters his most uber-cool catchphrase of the movie he folds away his Sony laptop. You just have to have one and hours later you have no idea why. It’s too late, the seed has been planted.
-
I’m a serial tenant. There’s nothing wrong with renting. On the whole it’s a worry-free life. If the washing machine breaks, I call my landlords and they are good people so they get it fixed up as soon as they can. I rent privately so my exposure to dreaded estate agents is (mercifully) low. I’m also free to move as frequently as my contract permits, which is flexibility I appreciate. However I get fed up with the limitations. It’s hard to have real pride in a place which is never really your own. And when I want to drill a hole in the wall I want to pick up a drill, not write a carefully worded email (with illustrations) to my landlord. I wouldn’t mind those tens of thousands of pounds sitting in my name in one of the most consistent investment markets either. Instead I give them to somebody else to make money for them.
And so it is that every six months or so I go through the optimistic but ultimately heartbreaking process of looking for a place of my own, with the eventual realisation that between arrangement fees, stamp duty, deposit, valuations and the rest, I just can’t afford to buy. Pretty much the only people I know who can have parental assistance which I would prefer to get by without even if the option existed.
Around a month ago, with a failed attempt to move due to inflated rental rates behind me, I embarked on this process once again. After a few days of enthusiastic chats with mortgage brokers I drew the sickening conclusion that I could only stretch to buying a house at this stage if I didn’t live in it. That is to say most brokers would offer me a buy-to-let mortgage with a better rate, lower tax, and higher LTV than an equivalent owner-occupier mortgage.
I am being priced out of the rental market and the government are doing their best to make sure that I can’t take that wild leap onto the property ladder by giving buy-to-let landlords a tax break.
I am struggling to see the motivation for such a move. Perhaps some genius saw an illustration of the current rental market and quizzically pondered “how can we relieve the burden on our strained rental market?” Having presumably been employed for his/her encyclopedic knowledge of economics and ability to think outside the box, supply and demand principles must have come to mind. And as supply typically comes before demand, in the phrase if not alphabetically, our hero rushed to the conclusion that we must get more individuals investing in properties they intend to let. And as such, eyes straining from the glare of the light bulb above his head, Johnny Treasury drafted a range of incentives to encourage those potential buy-to-let homeowners in search of additional income through extended borrowing against the incomes of their future tenants.
I could ramble on for hours. And no, I’m not qualified to. Adam Smith I am not. But I do have to get to the bank before I miss my landlord’s next mortgage payment.
-
Central London was buzzing today as thousands of protesters came together at ‘the wave’ climate change demonstration. I weaved amongst the crowds of experienced rally veterans, families, charities and students with my camera in hand trying to avoid the rain and capture the mood.
Whilst marching with the London Youth Labour group we were joined by Ed Miliband and Lord Mandelson, who showed some grit, spending over an hour surrounded by hundreds of individuals eager to impress upon these very politicians just what we expect from them at the upcoming Copenhagen climate talks.
Purchase