55502f40dc8b7c769880b10874abc9d0

This is a snippet to create a dict from one of my models.
I think that setting_context could be generated much more easily than what I'm doing here, just from reading about the different list and object comprehension functions, but I don't fully understand how to use them.

from django.db import models

# Create your models here.
class Setting(models.Model):
	description = models.CharField( max_length=256, blank=True )
	name = models.SlugField()
	value = models.CharField( max_length=128 )
	
	def get_context():
		settings = Setting.objects.all()
		settings = list(settings)
		setting_context = {}
		for setting in settings:
			setting_context[setting.name] = setting.value
		return setting_context

Refactorings

No refactoring yet !

833bfbcc9940cfcf0af6def751c23b05

Matthew Schinckel

February 22, 2010, February 22, 2010 11:09, permalink

1 rating. Login to rate!

This should really be in a custom manager, since it affects/uses all of the rows, not just one object.

from django.db import models

# Create your models here.
class Setting(models.Model):
	description = models.CharField( max_length=256, blank=True )
	name = models.SlugField()
	value = models.CharField( max_length=128 )
	
	def get_context():
		return Setting.objects.values()
1c014f0c48fc85edb8e8e28a1e8bb8ae

Sam Thomson

March 2, 2010, March 02, 2010 18:48, permalink

1 rating. Login to rate!

This uses list comprehension like you're looking for

from django.db import models

# Create your models here.
class Setting(models.Model):
	description = models.CharField( max_length=256, blank=True )
	name = models.SlugField()
	value = models.CharField( max_length=128 )
	
	def get_context():
		settings = Setting.objects.all()
		return dict([(setting.name, setting.value) for setting in settings])

Your refactoring





Format Copy from initial code

or Cancel