Snippet List
Adds a templatetag that works like an if block, but . The one and only argument is a float that reflects the percentage chance. It defaults to .2, %20.
{% sometimes %}
<img src='spy_behind_sniper.jpg'/>
{% else %}
<img src='sniper.jpg'/>
{% endsometimes %}
-- or --
{% sometimes .001 %}
You win!
{% else %}
Sorry, not a winner. Play again!
{% endsometimes %}
-- or --
{% sometimes .5 %}
This shows up half the time.
{% endsometimes %}
This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript.
**Example** (models.py):
from django.db import models
from jsonfield import JSONField
class Sequence(models.Model):
name = models.CharField(maxlength=25)
list = JSONField()
**Example** (shell):
fib = Sequence(name='Fibonacci')
fib.list = [0, 1, 1, 2, 3, 5, 8]
fib.save()
fib = Sequence.objects.get(name='Fibonacci')
fib.list.append(13)
print fib.list
[0, 1, 1, 2, 3, 5, 8, 13]
fib.get_list_json()
"[0, 1, 1, 2, 3, 5, 8, 13]"
*Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.
- models
- model
- json
- db
- field
- json-field
deadwisdom has posted 2 snippets.