Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Created June 20, 2011 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdickinson/1035178 to your computer and use it in GitHub Desktop.
Save chrisdickinson/1035178 to your computer and use it in GitHub Desktop.
ormnomnom rewrite.
{models, Author, Book} = require './models'
{connection} = require 'ormnomnom'
conn = connection.Connection.get_connection 'default'
models.db_creation 'default', yes, ->
create_book = Book.objects.create
author:Author.objects.get_or_create {first_name:'Cormac', last_name:'McCarthy', slug:'cormac-mccarthy'}
title:'Blood Meridian'
slug:'blood-meridian'
desc:'A book about violence and cowboys.'
# `create_book` is an EventEmitter AND a function.
create_book.on 'data', (book)->
console.log "Created #{book} with id of #{book.pk}"
# likewise, so is `book.author()`.
book.author() (err, author)->
console.log "using #{author} with id of #{author.pk}"
# you can join across foreign keys in filters
books = Book.objects.filter
author__first_name:'Cormac'
# for each book returned, log its name.
books.each (book)->
console.log "Got #{book}, #{book.pk}"
# we're done here.
books conn.close.bind conn
require('coffee-script');
require('./example');
{models} = require 'ormnomnom'
models.configure 'default',
backend:'ormnomnom/lib/backends/postgres'
name:'testdb'
exports.models =
models.namespace 'authors', (ns)->
Author = ns.create 'Author'
Author.schema
first_name:models.CharField {max_length:255}
last_name:models.CharField {max_length:255}
slug:models.CharField {max_length:255}
Author.meta
order_by:['last_name', 'first_name']
Author::toString =->
"<Author: \"#{@get_full_name()}\">"
Author::get_full_name = ->
[@first_name, @last_name].join ' '
Book = ns.create 'Book'
Book.schema
author: models.ForeignKey Author
title: models.CharField {max_length:255}
slug: models.CharField {max_length:255}
desc: models.TextField
Book::toString =->
"<Book: \"#{@title}\">"
exports.Author = Author
exports.Book = Book
$ node index.js
Created <Book: "Blood Meridian"> with id of 6
using <Author: "Cormac McCarthy"> with id of 1
Got <Book: "Blood Meridian">, 1
Got <Book: "Blood Meridian">, 2
Got <Book: "Blood Meridian">, 3
Got <Book: "Blood Meridian">, 4
Got <Book: "Blood Meridian">, 5
Got <Book: "Blood Meridian">, 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment