Showing posts with label model. Show all posts
Showing posts with label model. Show all posts

Apr 13, 2012

Testing models, forms

Form
Django Forms Deep Dive - Nathan R. Yergler
import unittest

class FormTests(unittest.TestCase):
    def test_validation(self):
        form_data = {
            'name': 'X' * 300,
        }

        form = ContactForm(data=form_data)
        self.assertFalse(form.is_valid())
Eventbrite just released a library on GitHub called rebar – https://github.com/eventbrite/rebar
from rebar.testing import flatten_to_dict

form_data = flatten_to_dict(ContactForm())
form_data.update({
        'name': 'X' * 300,
    })
form = ContactForm(data=form_data)
assert(not form.is_valid())
ModelForm
class ModelFormTests(unittest.TestCase):
    def test_validation(self):
        form_data = {
            'name': 'Test Name',
        }

        form = ContactForm(data=form_data)
        self.assert_(form.is_valid())
        self.assertEqual(form.instance.name, 'Test Name')

        form.save()

        self.assertEqual(
            Contact.objects.get(id=form.instance.id).name,
            'Test Name'
        )
FormSet
from rebar.testing import flatten_to_dict, empty_form_data

formset = ContactFormSet()
form_data = flatten_to_dict(formset)
form_data.update(
    empty_form_data(formset, len(formset))
)
Model
Fast test, slow test by Gary Bernhardt
def test_that_spam_posts_are_hidden(self):
    post = Post(mark_post_as_spam=True)
    discussion = Discussion(posts=[post])
    assert discussion.visible_posts == []

Jan 20, 2012

How to override the verbose name of a superclass model field in django

class SuperFoo(models.Model):
    name = models.CharField('name of SuperFoo instance', max_length=50)
    ...

class Foo(SuperFoo):
    ... # do something that changes verbose_name of name field of SuperFoo
    Foo._meta.get_field('name').verbose_name = 'Whatever'

Jan 11, 2012

How do you reload a Django model module using the interactive interpreter

from django.db.models.loading import AppCache
cache = AppCache()

for app in cache.get_apps():
    __import__(app.__name__)
    reload(app)

from django.utils.datastructures import SortedDict
cache.app_store = SortedDict()
cache.app_models = SortedDict()
cache.app_errors = {}
cache.handled = {}
cache.loaded = False

Dec 18, 2011

Django model to dict

from django.forms.models import model_to_dict
model_to_dict(intance, fields=[], exclude=[])

Jul 4, 2011

Making Changes to a Database Schema

Adding Fields

  1. Add the field to your model.
  2. Run manage.py sqlall [yourapp] to see the new CREATE TABLE statement for the model. Note the column definition for the new field.
  3. Start your database’s interactive shell (e.g., psql or mysql, or you can use manage.py dbshell). Execute an ALTER TABLE statement that adds your new column.

Adding NOT NULL Columns

BEGIN;
ALTER TABLE books_book ADD COLUMN num_pages integer;
UPDATE books_book SET num_pages=0;
ALTER TABLE books_book ALTER COLUMN num_pages SET NOT NULL;
COMMIT;

Removing Fields

  1. Remove the field’s code from your model class and restart the Web server.
  2. Remove the column from your database, using a command like this: 
    ALTER TABLE books_book DROP COLUMN num_pages;
Removing Many-to-Many Fields
  1. Remove the ManyToManyField code from your model class and restart the Web server.
  2. Remove the many-to-many table from your database, using a command like this:
    DROP TABLE books_book_authors;

Using South ;)

South brings migrations to Django applications. Its main objectives are to provide a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications. 

Jun 20, 2011

Quick and pritty iteration

qs = Item.objects.filter(...).values_list('title', 'amount', 'price')

for title, amount, price in qs:
    print title, amount
    total += amount * price