Skip to content

Commit

Permalink
added objects.create; changed lookups and added 'in' lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
monobot committed May 19, 2017
1 parent 05e5aed commit 0b0fb28
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 15 deletions.
2 changes: 1 addition & 1 deletion asyncorm/fields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def set_field_name(self, field_name):


class PkField(Field):
internal_type = object
internal_type = int
creation_string = 'serial primary key'

def __init__(self, field_name='id', unique=False, null=False):
Expand Down
34 changes: 23 additions & 11 deletions asyncorm/manager/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@

__all__ = ['ModelManager', 'Queryset']

MIDDLE_OPERATOR = {
'gt': '>',
'lt': '<',
'gte': '>=',
'lte': '<=',
LOOKUP_OPERATOR = {
'gt': '{} > {}',
'lt': '{} < {}',
'gte': '{} >= {}',
'lte': '{} <= {}',
'in': '{} = ANY (array[{}])'
}


Expand Down Expand Up @@ -177,14 +178,14 @@ def calc_filters(self, kwargs, exclude):

for k, v in kwargs.items():
# we format the key, the conditional and the value
middle = '='
operator = '{} = {}'
if len(k.split('__')) > 1:
k, middle = k.split('__')
middle = MIDDLE_OPERATOR[middle]
k, operator = k.split('__')
operator = LOOKUP_OPERATOR[operator]

field = getattr(self.model, k)

if middle == '=' and isinstance(v, tuple):
if operator == '{} = {}' and isinstance(v, tuple):
if len(v) != 2:
raise QuerysetError(
'Not a correct tuple definition, filter '
Expand All @@ -199,9 +200,14 @@ def calc_filters(self, kwargs, exclude):
)
)
else:
v = field.sanitize_data(v)
if isinstance(v, (list, tuple)):
# check they are correct items and serialize
v = ','.join([str(field.sanitize_data(si)) for si in v])
else:
v = field.sanitize_data(v)

filters.append(
bool_string + '{}{}{}'.format(field.field_name, middle, v)
bool_string + operator.format(field.field_name, v)
)

return filters
Expand Down Expand Up @@ -384,3 +390,9 @@ async def delete(self, instanced_model):
)
}]
return await self.db_request(db_request)

async def create(self, **kwargs):
n_object = self.model(**kwargs)
await n_object.save()

return n_object
8 changes: 6 additions & 2 deletions asyncorm/model/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@ def __new__(cls, clsname, bases, clsdict):
defined_meta = clsdict.pop('Meta', None)

if defined_meta:
# For a modelserializer when check that has it correctly defined
# has a model
if hasattr(defined_meta, 'model'):
base_class.model = getattr(defined_meta, 'model')
else:
raise SerializerError(
'The serializer has to define it refeers to'
'The serializer has to define the model it\'s serializing'
)
# has fields
if hasattr(defined_meta, 'fields'):
base_class._fields = getattr(defined_meta, 'fields')
else:
raise SerializerError(
'The serializer has to define it refeers to'
'The serializer has to define the fields\'s to serialize'
)

return base_class
Expand Down Expand Up @@ -57,6 +60,7 @@ def serialize(cls, instanced_model):
)

for f in cls._fields:
# if the serializer class has an specific serializer for that field
if hasattr(cls, f):
serializer = getattr(cls, f)
if isinstance(serializer, SerializerMethod):
Expand Down
1 change: 1 addition & 0 deletions tests/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

drop_tables = ['Publisher', 'Author', 'library', 'Organization', 'Developer',
'Client', 'Developer_Organization', 'Author_Publisher',
'Appointment', 'Reader'
]


Expand Down
47 changes: 47 additions & 0 deletions tests/manage_tests.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from datetime import datetime
from datetime import timedelta

from asyncorm.exceptions import *
from asyncorm.fields import *

from .testapp.models import Author, Book
from .testapp2.models import Appointment
from .test_helper import AioTestCase


Expand Down Expand Up @@ -156,6 +158,46 @@ async def test_filter(self):
queryset = Book.objects.filter(id__gt=2800)
self.assertEqual(await queryset.count(), 0)

async def test_comparisons_dates(self):
today = datetime.now()
await Appointment.objects.create(
name='app1', date=today + timedelta(days=1)
)
await Appointment.objects.create(
name='app2', date=today
)
await Appointment.objects.create(
name='app3', date=today - timedelta(days=1)
)

self.assertEqual(
await Appointment.objects.all().count(), 3)
self.assertEqual(
await Appointment.objects.filter(date__gt=today).count(),
1
)
self.assertEqual(
await Appointment.objects.filter(date__gte=today).count(),
2
)
self.assertEqual(
await Appointment.objects.filter(date__lt=today).count(),
1
)
self.assertEqual(
await Appointment.objects.filter(
date__lte=today + timedelta(days=1)
).count(),
3
)

async def test_in_lookput(self):
queryset = Book.objects.filter(id__in=(1, 2, 56, 456))
self.assertEqual(await queryset.count(), 3)

queryset = Book.objects.filter(name__in=('1', '2', '56'))
self.assertEqual(await queryset.count(), 0)

async def test_exclude(self):
queryset = Book.objects.exclude(id__gt=280)

Expand Down Expand Up @@ -188,3 +230,8 @@ async def test_get(self):
with self.assertRaises(QuerysetError) as exc:
await Book.objects.get(id=2800)
self.assertTrue('does not exist' in exc.exception.args[0])

async def test_create(self):
author = await Author.objects.create(**{'name': 'Juanito', 'age': 73})

self.assertTrue(isinstance(author, Author))
26 changes: 25 additions & 1 deletion tests/model_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ class Meta:
model = Book
fields = ['name', 'content', ]

# complains i we try to serialize an incorrect model
# complains if we try to serialize an incorrect model
with self.assertRaises(SerializerError) as exc:
author = Author()
BookSerializer().serialize(author)
Expand All @@ -199,3 +199,27 @@ class Meta:

serialized_book = BookSerializer().serialize(book)
self.assertEqual(serialized_book.get('name'), 'this is a new name')

# complains if we have a model serializer without model
with self.assertRaises(SerializerError) as exc:

class NooneSerializer(ModelSerializer):

class Meta:
fields = ['name', 'content', ]
self.assertEqual(
'The serializer has to define the model it\'s serializing',
exc.exception.args[0]
)

# complains if we have a model serializer without model
with self.assertRaises(SerializerError) as exc:

class Noone2Serializer(ModelSerializer):

class Meta:
model = Book
self.assertEqual(
'The serializer has to define the fields\'s to serialize',
exc.exception.args[0]
)
5 changes: 5 additions & 0 deletions tests/testapp2/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ class Developer(Model):
class Client(Model):
name = CharField(max_length=10)
dev = ForeignKey(foreign_key='Developer')


class Appointment(Model):
name = CharField(max_length=50)
date = DateField()

0 comments on commit 0b0fb28

Please sign in to comment.