Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test cases for ORM queries mentioned in book and some typo fix #53

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
edefe66
typo fix
Shekharnunia Aug 4, 2020
1f4a6c4
testcases are added for first 7 sections of documentation query which…
Shekharnunia Aug 4, 2020
cb76803
Create django.yml
Shekharnunia Aug 4, 2020
2447112
Update django.yml
Shekharnunia Aug 4, 2020
0389847
Update django.yml
Shekharnunia Aug 4, 2020
fe6bf26
python decople added into requirements and sqlite database added into…
Shekharnunia Aug 4, 2020
5a6d161
complex subquery test case added into entities app and black formatti…
Shekharnunia Aug 5, 2020
bd47cf5
F expression test cases are added which will first check for simple F…
Shekharnunia Aug 5, 2020
2185750
Join operation test added which will verify if the given django orm q…
Shekharnunia Aug 5, 2020
fa7deff
test case for grouping queries are added
Shekharnunia Aug 5, 2020
31766c6
bulk create query test cases are added
Shekharnunia Aug 5, 2020
f802515
object copy query test care are written
Shekharnunia Aug 5, 2020
157751c
test case added to check that only single object will be created a model
Shekharnunia Aug 5, 2020
04e986a
test case for denormalized data is added
Shekharnunia Aug 5, 2020
6080409
black formatting applied for models and test files
Shekharnunia Aug 5, 2020
68a0ca8
test case for truncate query is added and for current working cursor …
Shekharnunia Aug 5, 2020
1156cb5
test case for storing date from string into datefield is added
Shekharnunia Aug 5, 2020
b86a910
test case for order by with case insensitivity is added
Shekharnunia Aug 5, 2020
538813e
test case of orderby on two fields is added
Shekharnunia Aug 5, 2020
320bd5f
test case for order by on foreignkey field is added
Shekharnunia Aug 6, 2020
fac8504
test case for orderby with annotation is added
Shekharnunia Aug 6, 2020
768ca9f
test case for one to one model relationship is added
Shekharnunia Aug 6, 2020
a022b0b
typo fix in one to many documentation page
Shekharnunia Aug 6, 2020
6b5404e
test case for one to many relation is added
Shekharnunia Aug 6, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/django.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Django CI

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest
strategy:
max-parallel: 4
matrix:
python-version: [3.6, 3.7, 3.8]

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install -r heroes_and_monsters/requirements.txt
- name: Run Tests
run: |
cd heroes_and_monsters && python manage.py test
6 changes: 1 addition & 5 deletions docs/notequal_query.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ Our SQL query for the above condition will look something like ::

.. image:: sqluser_notquery.png

Method 1 using exclude

.. code-block


Method 1 using exclude ::

>>> queryset = User.objects.exclude(id__lt=5)
>>> queryset
Expand Down
2 changes: 1 addition & 1 deletion docs/one_to_many.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ To define a many-to-one relationship, use `ForeignKey`.::
If you try to assign an object before saving it you will encounter a ValueError ::

>>> u3 = User(username='someuser', first_name='Some', last_name='User', email='[email protected]')
>>> Article.objects.create(headline="This is a test", pub_date=date(2018, 3, 7), reporter=u1)
>>> Article.objects.create(headline="This is a test", pub_date=date(2018, 3, 7), reporter=u3)
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.
Expand Down
2 changes: 1 addition & 1 deletion heroes_and_monsters/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
DATABASE_URL=postgres://umsra:umsra@localhost:5432/umsra
DATABASE_URL=sqlite:///db.sqlite3
export DATABASE_URL
78 changes: 43 additions & 35 deletions heroes_and_monsters/entities/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@ class Meta:
@classmethod
def truncate(cls):
with connection.cursor() as cursor:
cursor.execute('TRUNCATE TABLE "{0}" CASCADE'.format(cls._meta.db_table))

cursor.execute('DELETE FROM "{0}"'.format(cls._meta.db_table))

def __str__(self):
return self.name


from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType

# ...


class FlexCategory(models.Model):
name = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')

content_object = GenericForeignKey("content_type", "object_id")


class Origin(models.Model):
Expand All @@ -54,26 +54,24 @@ class Entity(models.Model):
GENDER_OTHERS = "Others/Unknown"

name = models.CharField(max_length=100)
alternative_name = models.CharField(
max_length=100, null=True, blank=True
)

alternative_name = models.CharField(max_length=100, null=True, blank=True)

category = models.ForeignKey(Category, on_delete=models.CASCADE)
flex_category = GenericRelation(FlexCategory, related_query_name='flex_category')
flex_category = GenericRelation(FlexCategory, related_query_name="flex_category")
origin = models.ForeignKey(Origin, on_delete=models.CASCADE)
gender = models.CharField(
max_length=100,
choices=(
(GENDER_MALE, GENDER_MALE),
(GENDER_FEMALE, GENDER_FEMALE),
(GENDER_OTHERS, GENDER_OTHERS),
)
),
)
description = models.TextField()

added_by = models.ForeignKey(settings.AUTH_USER_MODEL,
null=True, blank=True, on_delete=models.SET_NULL)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL
)
added_on = models.DateField(auto_now=True)

def __str__(self):
Expand All @@ -84,7 +82,6 @@ class Meta:


class Hero(Entity):

class Meta:
verbose_name_plural = "Heroes"

Expand All @@ -95,19 +92,21 @@ class Meta:
is_immortal = models.BooleanField(default=True)

benevolence_factor = models.PositiveSmallIntegerField(
help_text="How benevolent this hero is?",
default=50
help_text="How benevolent this hero is?", default=50
)
arbitrariness_factor = models.PositiveSmallIntegerField(
help_text="How arbitrary this hero is?",
default=50
help_text="How arbitrary this hero is?", default=50
)

headshot = models.ImageField(null=True, blank=True, upload_to="hero_headshots/")

# relationships
father = models.ForeignKey(
"self", related_name="children", null=True, blank=True, on_delete=models.SET_NULL
"self",
related_name="children",
null=True,
blank=True,
on_delete=models.SET_NULL,
)
mother = models.ForeignKey(
"self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL
Expand All @@ -116,12 +115,19 @@ class Meta:
"self", related_name="+", null=True, blank=True, on_delete=models.SET_NULL
)

def save(self, *args, **kwargs):
if not self.pk:
Category.objects.filter(pk=self.category_id).update(
hero_count=F("hero_count") + 1
)
super().save(*args, **kwargs)


class HeroProxy(Hero):

class Meta:
proxy = True


class Villain(Entity):
is_immortal = models.BooleanField(default=False)

Expand All @@ -134,9 +140,12 @@ class Villain(Entity):
is_unique = models.BooleanField(default=True)
count = models.PositiveSmallIntegerField(default=1)

# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# Category.objects.filter(pk=self.category_pk).update(villain_count=F(villain_count)+1)
def save(self, *args, **kwargs):
if not self.pk:
Category.objects.filter(pk=self.category_id).update(
villain_count=F("villain_count") + 1
)
super().save(*args, **kwargs)


class HeroAcquaintance(models.Model):
Expand All @@ -156,18 +165,17 @@ class Meta:
db_table = "entities_entity"


from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Hero, dispatch_uid="update_hero_count")
def update_hero_count(sender, **kwargs):
hero = kwargs['instance']
if hero.pk:
Category.objects.filter(pk=hero.category_id).update(hero_count=F('hero_count')+1)
# from django.db.models.signals import pre_save
# from django.dispatch import receiver

@receiver(pre_save, sender=Villain, dispatch_uid="update_villain_count")
def update_villain_count(sender, **kwargs):
villain = kwargs['instance']
if villain.pk:
Category.objects.filter(pk=villain.category_id).update(villain_count=F('villain_count')+1)
# @receiver(pre_save, sender=Hero, dispatch_uid="update_hero_count")
# def update_hero_count(sender, **kwargs):
# hero = kwargs['instance']
# if hero.pk:
# Category.objects.filter(pk=hero.category_id).update(hero_count=F('hero_count')+1)

# @receiver(pre_save, sender=Villain, dispatch_uid="update_villain_count")
# def update_villain_count(sender, **kwargs):
# villain = kwargs['instance']
# if villain.pk:
# Category.objects.filter(pk=villain.category_id).update(villain_count=F('villain_count')+1)
Loading