I’ve got a pretty good list of songs I like, and I wanted to copy them all to a USB stick for the car… So here’s the bash one-liner I wrote to take an m3u playlist and copy all the files to a new directory:
#!/bin/bash
cat playlist.m3u | grep -v '#' | \
while read i; do cp "${i}" /path/to/destination/ ; done
Django models automatically come with some very useful methods under the objects Manager. Methods like Model.objects.all(), Model.objects.filter() and Model.objects.get() work quite well.
But what if you are constantly using the same QuerySet over and over? You can either keep typing MyModel.objects.filter(way-to-many-kwargs).order_by(something).etc... over and over -or- extend the objects Manager with your own crazy method.
Let’s say you’ve got the following Model:
class MyModel(models.Model):
...
...
...
All you need to do is subclass Manager, add your method and override your model’s old Manager:
class MyModelManager(models.Manager):
def crazy_query(self):
...
# A bunch of queries, joins, logic, etc...
...
class MyModel(models.Model):
...
...
...
objects = MyModelManager()
In order to make a handy Documentation link available in the upper right portion of the Django admin site, simply add the admindocs app to your settings.py and the admindocs urls to your urls.py
# In your settings.py:
INSTALLED_APPS = (
...
'django.contrib.admindocs',
...
)
# In your urls.py:
urlpatterns = patterns('',
...
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
...
)
NOTE: The admindocs urlconf must precede the admin site urlconf to work properly.
I had almost given up on my dream of hierarchical (multi-level) categories sorted by their self-referential parent to form a tree. Almost, but I finally figured it out.
I’m not sure if it’s a hack or the “one obvious way”, as Tim Peters puts it (probably not), but it works and I’m using it.
The whole problem starts with a simple model:
class Category(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey('self', blank=True,
null=True, related_name='child')
def __unicode__(self):
if self.parent:
prefix = str(self.parent)
else:
return self.name
return ' > '.join((prefix,self.name))
It works great for categories with sub categories. And when you call the __unicode__() method, it even spits out the whole ancestry to the category (eg. u'GrandParent > Parent > Category').
But alas, as soon as you try to sort them by their parents, you find out that the full name is not a real field and you can’t order by fake fields. Of course you might get the bright idea to add the order_with_respect_to = 'parent' Meta class attribute, but that will only lead you here.