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

Support filtering on a values list subquery. #54

Merged
merged 2 commits into from
Oct 30, 2017

Conversation

donkirkby
Copy link
Collaborator

It looks like I removed an exception handler that I shouldn't have back in February. This pull request puts the exception handler back, along with a test that shows when it's needed.

Here's a snippet that shows how the real Django query set supports filtering by a values list:

# Tested with Django 1.9.2
import sys

import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import connections, models, DEFAULT_DB_ALIAS
from django.db.models.base import ModelBase

NAME = 'udjango'


def main():
    setup()

    class Car(models.Model):
        model = models.CharField(max_length=25, blank=True, null=True)
        year = models.IntegerField()

    syncdb(Car)

    Car.objects.create(model='Gremlin', year=1970)
    Car.objects.create(model='Pinto', year=1971)
    Car.objects.create(model='Smart Car', year=2000)

    old_cars = Car.objects.filter(year__lt=1990)
    old_car_pks = old_cars.values_list("pk", flat=True)

    matches = Car.objects.filter(pk__in=old_car_pks)

    assert list(old_cars) == list(matches)


def setup():
    DB_FILE = NAME + '.db'
    with open(DB_FILE, 'w'):
        pass  # wipe the database
    settings.configure(
        DEBUG=True,
        DATABASES={
            DEFAULT_DB_ALIAS: {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': DB_FILE}},
        LOGGING={'version': 1,
                 'disable_existing_loggers': False,
                 'formatters': {
                    'debug': {
                        'format': '%(asctime)s[%(levelname)s]'
                                  '%(name)s.%(funcName)s(): %(message)s',
                        'datefmt': '%Y-%m-%d %H:%M:%S'}},
                 'handlers': {
                    'console': {
                        'level': 'DEBUG',
                        'class': 'logging.StreamHandler',
                        'formatter': 'debug'}},
                 'root': {
                    'handlers': ['console'],
                    'level': 'WARN'},
                 'loggers': {
                    "django.db": {"level": "WARN"}}})
    app_config = AppConfig(NAME, sys.modules['__main__'])
    apps.populate([app_config])
    django.setup()
    original_new_func = ModelBase.__new__

    @staticmethod
    def patched_new(cls, name, bases, attrs):
        if 'Meta' not in attrs:
            class Meta:
                app_label = NAME
            attrs['Meta'] = Meta
        return original_new_func(cls, name, bases, attrs)
    ModelBase.__new__ = patched_new


def syncdb(model):
    """ Standard syncdb expects models to be in reliable locations.

    Based on https://github.com/django/django/blob/1.9.3
    /django/core/management/commands/migrate.py#L285
    """
    connection = connections[DEFAULT_DB_ALIAS]
    with connection.schema_editor() as editor:
        editor.create_model(model)

main()

@donkirkby donkirkby added the bug label Oct 30, 2017
@donkirkby
Copy link
Collaborator Author

That tox failure is weird. I had the same thing happen on my workstation, but it worked the second time I ran it. I'll see if I can figure out what's wrong.

@codecov-io
Copy link

Codecov Report

Merging #54 into master will not change coverage.
The diff coverage is 100%.

Impacted file tree graph

@@          Coverage Diff          @@
##           master    #54   +/-   ##
=====================================
  Coverage     100%   100%           
=====================================
  Files           6      6           
  Lines         700    703    +3     
=====================================
+ Hits          700    703    +3
Impacted Files Coverage Δ
django_mock_queries/utils.py 100% <100%> (ø) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e2e1151...87bfb3f. Read the comment docs.

@stphivos stphivos merged commit 07f1cef into stphivos:master Oct 30, 2017
@stphivos
Copy link
Owner

Cool thanks for noticing!

@donkirkby donkirkby deleted the no-pk-attribute branch October 30, 2017 22:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants