class FK1(models.Model):
    f1 = models.TextField()
    f2 = models.TextField() class Annotation(models.Model):
    name = models.CharField(max_length=10)
    tag = models.ForeignKey(Tag, models.CASCADE)
    notes = models.ManyToManyField(Note)

    def __str__(self):
        return self.name class Article(models.Model):
    name = models.CharField(max_length=20)
    created = models.DateTimeField()

    def __str__(self):
        return self.name class Author(models.Model):
    name = models.CharField(max_length=10)
    num = models.IntegerField(unique=True)
    extra = models.ForeignKey(ExtraInfo, models.CASCADE)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name class BaseA(models.Model):
    a = models.ForeignKey(FK1, models.SET_NULL, null=True)
    b = models.ForeignKey(FK2, models.SET_NULL, null=True)
    c = models.ForeignKey(FK3, models.SET_NULL, null=True) class Book(models.Model):
    title = models.TextField()
    chapter = models.ForeignKey('Chapter', models.CASCADE) class CategoryItem(models.Model):
    category = models.ForeignKey(SimpleCategory, models.CASCADE)

    def __str__(self):
        return "category item: " + str(self.category) class CategoryRelationship(models.Model):
    first = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='first_rel')
    second = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='second_rel') class Celebrity(models.Model):
    name = models.CharField("Name", max_length=20)
    greatest_fan = models.ForeignKey("Fan", models.SET_NULL, null=True, unique=True)

    def __str__(self):
        return self.name class Channel(models.Model):
    programs = models.ManyToManyField(Program)
    identifier = models.OneToOneField(Identifier, models.CASCADE) class Chapter(models.Model):
    title = models.TextField()
    paragraph = models.ForeignKey('Paragraph', models.CASCADE) class Child(models.Model):
    person = models.OneToOneField(Member, models.CASCADE, primary_key=True)
    parent = models.ForeignKey(Member, models.CASCADE, related_name="children") class ChildObjectA(ObjectA):
    pass class Classroom(models.Model):
    school = models.ForeignKey(School, models.CASCADE)
    students = models.ManyToManyField(Student, related_name='classroom') class Company(models.Model):
    name = models.CharField(max_length=128)
    employees = models.ManyToManyField(Person, related_name='employers', through='Employment')

    def __str__(self):
        return self.name class Cover(models.Model):
    title = models.CharField(max_length=50)
    item = models.ForeignKey(Item, models.CASCADE)

    class Meta:
        ordering = ['item']

    def __str__(self):
        return self.title class CustomPk(models.Model):
    name = models.CharField(max_length=10, primary_key=True)
    extra = models.CharField(max_length=10)

    class Meta:
        ordering = ['name', 'extra'] class CustomPkTag(models.Model):
    id = models.CharField(max_length=20, primary_key=True)
    custom_pk = models.ManyToManyField(CustomPk)
    tag = models.CharField(max_length=20) class Detail(models.Model):
    data = models.CharField(max_length=10) class DumbCategory(models.Model):
    pass class Eaten(models.Model):
    food = models.ForeignKey(Food, models.SET_NULL, to_field="name", null=True)
    meal = models.CharField(max_length=20)

    def __str__(self):
        return "%s at %s" % (self.food, self.meal) class Employment(models.Model):
    employer = models.ForeignKey(Company, models.CASCADE)
    employee = models.ForeignKey(Person, models.CASCADE)
    title = models.CharField(max_length=128) class ExtraInfo(models.Model):
    info = models.CharField(max_length=100)
    note = models.ForeignKey(Note, models.CASCADE, null=True)
    value = models.IntegerField(null=True)

    class Meta:
        ordering = ['info']

    def __str__(self):
        return self.info class Fan(models.Model):
    fan_of = models.ForeignKey(Celebrity, models.CASCADE) class Food(models.Model):
    name = models.CharField(max_length=20, unique=True)

    def __str__(self):
        return self.name class Identifier(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name class Individual(models.Model):
    alive = models.BooleanField()

    class Meta:
        db_table = 'Individual' class Item(models.Model):
    name = models.CharField(max_length=10)
    created = models.DateTimeField()
    modified = models.DateTimeField(blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True)
    creator = models.ForeignKey(Author, models.CASCADE)
    note = models.ForeignKey(Note, models.CASCADE)

    class Meta:
        ordering = ['-note', 'name']

    def __str__(self):
        return self.name class Job(models.Model):
    name = models.CharField(max_length=20, unique=True)

    def __str__(self):
        return self.name class JobResponsibilities(models.Model):
    job = models.ForeignKey(Job, models.CASCADE, to_field='name')
    responsibility = models.ForeignKey('Responsibility', models.CASCADE, to_field='description') class Join(models.Model):
    a = models.ForeignKey(LeafA, models.CASCADE)
    b = models.ForeignKey(LeafB, models.CASCADE) class LeafA(models.Model):
    data = models.CharField(max_length=10)

    def __str__(self):
        return self.data class LeafB(models.Model):
    data = models.CharField(max_length=10) class LoopX(models.Model):
    y = models.ForeignKey('LoopY', models.CASCADE)

    class Meta:
        ordering = ['y'] class LoopZ(models.Model):
    z = models.ForeignKey('self', models.CASCADE)

    class Meta:
        ordering = ['z'] class ManagedModel(models.Model):
    data = models.CharField(max_length=10)
    tag = models.ForeignKey(Tag, models.CASCADE)
    public = models.BooleanField(default=True)

    objects = CustomManager()
    normal_manager = models.Manager()

    def __str__(self):
        return self.data class Member(models.Model):
    name = models.CharField(max_length=10)
    details = models.OneToOneField(Detail, models.CASCADE, primary_key=True)

    objects = MemberManager() class ModelA(models.Model):
    name = models.TextField()
    b = models.ForeignKey(ModelB, models.SET_NULL, null=True)
    d = models.ForeignKey(ModelD, models.CASCADE) class ModelB(models.Model):
    name = models.TextField()
    c = models.ForeignKey(ModelC, models.CASCADE) class ModelC(models.Model):
    name = models.TextField() class ModelD(models.Model):
    name = models.TextField() class MyObject(models.Model):
    parent = models.ForeignKey('self', models.SET_NULL, null=True, blank=True, related_name='children')
    data = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True) class NamedCategory(DumbCategory):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name class Node(models.Model):
    num = models.IntegerField(unique=True)
    parent = models.ForeignKey("self", models.SET_NULL, to_field="num", null=True)

    def __str__(self):
        return "%s" % self.num class Note(models.Model):
    note = models.CharField(max_length=100)
    misc = models.CharField(max_length=10)
    tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True)

    class Meta:
        ordering = ['note']

    def __str__(self):
        return self.note

    def __init__(self, *args, **kwargs):
        super(Note, self).__init__(*args, **kwargs)
        # Regression for #13227 -- having an attribute that
        # is unpicklable doesn't stop you from cloning queries
        # that use objects of that type as an argument.
        self.lock = threading.Lock() class NullableName(models.Model):
    name = models.CharField(max_length=20, null=True)

    class Meta:
        ordering = ['id'] class Number(models.Model):
    num = models.IntegerField()

    def __str__(self):
        return six.text_type(self.num) class ObjectA(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    def __iter__(self):
        # Ticket #23721
        assert False, 'type checking should happen without calling model __iter__' class ObjectB(models.Model):
    name = models.CharField(max_length=50)
    objecta = models.ForeignKey(ObjectA, models.CASCADE)
    num = models.PositiveSmallIntegerField()

    def __str__(self):
        return self.name class ObjectC(models.Model):
    name = models.CharField(max_length=50)
    objecta = models.ForeignKey(ObjectA, models.SET_NULL, null=True)
    objectb = models.ForeignKey(ObjectB, models.SET_NULL, null=True)
    childobjecta = models.ForeignKey(ChildObjectA, models.SET_NULL, null=True, related_name='ca_pk')

    def __str__(self):
        return self.name class OneToOneCategory(models.Model):
    new_name = models.CharField(max_length=15)
    category = models.OneToOneField(SimpleCategory, models.CASCADE)

    def __str__(self):
        return "one2one " + self.new_name class Order(models.Model):
    id = models.IntegerField(primary_key=True)

    class Meta:
        ordering = ('pk', )

    def __str__(self):
        return '%s' % self.pk class OrderItem(models.Model):
    order = models.ForeignKey(Order, models.CASCADE, related_name='items')
    status = models.IntegerField()

    class Meta:
        ordering = ('pk', )

    def __str__(self):
        return '%s' % self.pk class Page(models.Model):
    text = models.TextField() class Paragraph(models.Model):
    text = models.TextField()
    page = models.ManyToManyField('Page') class Person(models.Model):
    name = models.CharField(max_length=128) class Plaything(models.Model):
    name = models.CharField(max_length=10)
    others = models.ForeignKey(RelatedObject, models.SET_NULL, null=True)

    class Meta:
        ordering = ['others']

    def __str__(self):
        return self.name class PointerA(models.Model):
    connection = models.ForeignKey(SharedConnection, models.CASCADE) class Program(models.Model):
    identifier = models.OneToOneField(Identifier, models.CASCADE) class ProxyCategory(DumbCategory):
    class Meta:
        proxy = True class ProxyObjectA(ObjectA):
    class Meta:
        proxy = True class ProxyObjectB(ObjectB):
    class Meta:
        proxy = True class Ranking(models.Model):
    rank = models.IntegerField()
    author = models.ForeignKey(Author, models.CASCADE)

    class Meta:
        # A complex ordering specification. Should stress the system a bit.
        ordering = ('author__extra__note', 'author__name', 'rank')

    def __str__(self):
        return '%d: %s' % (self.rank, self.author.name) class Related(models.Model):
    custom = models.ForeignKey(CustomPk, models.CASCADE, null=True) class RelatedIndividual(models.Model):
    related = models.ForeignKey(Individual, models.CASCADE, related_name='related_individual')

    class Meta:
        db_table = 'RelatedIndividual' class RelatedObject(models.Model):
    single = models.ForeignKey(SingleObject, models.SET_NULL, null=True)
    f = models.IntegerField(null=True)

    class Meta:
        ordering = ['single'] class Report(models.Model):
    name = models.CharField(max_length=10)
    creator = models.ForeignKey(Author, models.SET_NULL, to_field='num', null=True)

    def __str__(self):
        return self.name class ReportComment(models.Model):
    report = models.ForeignKey(Report, models.CASCADE) class ReservedName(models.Model):
    name = models.CharField(max_length=20)
    order = models.IntegerField()

    def __str__(self):
        return self.name class Responsibility(models.Model):
    description = models.CharField(max_length=20, unique=True)
    jobs = models.ManyToManyField(Job, through=JobResponsibilities,
                                  related_name='responsibilities')

    def __str__(self):
        return self.description class School(models.Model):
    pass class SharedConnection(models.Model):
    data = models.CharField(max_length=10)

    def __str__(self):
        return self.data class SimpleCategory(models.Model):
    name = models.CharField(max_length=15)

    def __str__(self):
        return self.name class SingleObject(models.Model):
    name = models.CharField(max_length=10)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name class SpecialCategory(SimpleCategory):
    special_name = models.CharField(max_length=15)

    def __str__(self):
        return self.name + " " + self.special_name class Staff(models.Model):
    name = models.CharField(max_length=10)

    def __str__(self):
        return self.name class StaffUser(BaseUser):
    staff = models.OneToOneField(Staff, models.CASCADE, related_name='user')

    def __str__(self):
        return self.staff class Student(models.Model):
    school = models.ForeignKey(School, models.CASCADE) class Tag(models.Model):
    name = models.CharField(max_length=10)
    parent = models.ForeignKey(
        'self',
        models.SET_NULL,
        blank=True, null=True,
        related_name='children',
    )
    category = models.ForeignKey(NamedCategory, models.SET_NULL, null=True, default=None)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name class Task(models.Model):
    title = models.CharField(max_length=10)
    owner = models.ForeignKey(BaseUser, models.CASCADE, related_name='owner')
    creator = models.ForeignKey(BaseUser, models.CASCADE, related_name='creator')

    def __str__(self):
        return self.title class Ticket21203Child(models.Model):
    childid = models.AutoField(primary_key=True)
    parent = models.ForeignKey(Ticket21203Parent, models.CASCADE) class Ticket21203Parent(models.Model):
    parentid = models.AutoField(primary_key=True)
    parent_bool = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now=True) class Ticket23605A(Ticket23605AParent):
    pass class Ticket23605B(models.Model):
    modela_fk = models.ForeignKey(Ticket23605A, models.CASCADE)
    modelc_fk = models.ForeignKey("Ticket23605C", models.CASCADE)
    field_b0 = models.IntegerField(null=True)
    field_b1 = models.BooleanField(default=False) class Ticket23605C(models.Model):
    field_c0 = models.FloatField() class TvChef(Celebrity):
    pass class Valid(models.Model):
    valid = models.CharField(max_length=10)
    parent = models.ManyToManyField('self')

    class Meta:
        ordering = ['valid'] class X(models.Model):
    y = models.ForeignKey('Y', models.CASCADE)
import datetime
import pickle
import unittest
import django
from collections import OrderedDict
from operator import attrgetter
from django.core.exceptions import FieldError
    from django.core.exceptions import EmptyResultSet
from django.db import DEFAULT_DB_ALIAS, connection
from django.db.models import Count, F, Q
from django.db.models.sql.constants import LOUTER
from django.db.models.sql.where import NothingNode, WhereNode
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext
from django.utils import six
from django.utils.six.moves import range
from .models import (
    FK1, Annotation, Article, Author, BaseA, Book, CategoryItem,
    CategoryRelationship, Celebrity, Channel, Chapter, Child, ChildObjectA,
    Classroom, Company, Cover, CustomPk, CustomPkTag, Detail, DumbCategory,
    Eaten, Employment, ExtraInfo, Fan, Food, Identifier, Individual, Item, Job,
    JobResponsibilities, Join, LeafA, LeafB, LoopX, LoopZ, ManagedModel,
    Member, ModelA, ModelB, ModelC, ModelD, MyObject, NamedCategory, Node,
    Note, NullableName, Number, ObjectA, ObjectB, ObjectC, OneToOneCategory,
    Order, OrderItem, Page, Paragraph, Person, Plaything, PointerA, Program,
    ProxyCategory, ProxyObjectA, ProxyObjectB, Ranking, Related,
    RelatedIndividual, RelatedObject, Report, ReportComment, ReservedName,
    Responsibility, School, SharedConnection, SimpleCategory, SingleObject,
    SpecialCategory, Staff, StaffUser, Student, Tag, Task, Ticket21203Child,
    Ticket21203Parent, Ticket23605A, Ticket23605B, Ticket23605C, TvChef, Valid,
    X,
)
        # The numbers amount is picked to force three different IN batches
        # for Oracle, yet to be less than 2100 parameter limit for MSSQL.
        numbers = list(range(2050))
        Number.objects.all().delete()
        Number.objects.bulk_create(Number(num=num) for num in numbers)
        self.assertEqual(
            Number.objects.filter(num__in=numbers[:1000]).count(),
            1000
        )
        self.assertEqual(
            Number.objects.filter(num__in=numbers[:1001]).count(),
            1001
        )
        self.assertEqual(
            Number.objects.filter(num__in=numbers[:2000]).count(),
            2000
        )
        self.assertEqual(
            Number.objects.filter(num__in=numbers).count(),
            len(numbers)
        )


class UnionTests(unittest.TestCase):
    """
    Tests for the union of two querysets. Bug #12252.
    """
    @classmethod
    def setUpTestData(cls):
        objectas = []
        objectbs = []
        objectcs = []
        a_info = ['one', 'two', 'three']
        for name in a_info:
            o = ObjectA(name=name)
            o.save()
            objectas.append(o)
        b_info = [('un', 1, objectas[0]), ('deux', 2, objectas[0]), ('trois', 3, objectas[2])]
        for name, number, objecta in b_info:
            o = ObjectB(name=name, num=number, objecta=objecta)
            o.save()
            objectbs.append(o)
        c_info = [('ein', objectas[2], objectbs[2]), ('zwei', objectas[1], objectbs[1])]
        for name, objecta, objectb in c_info:
            o = ObjectC(name=name, objecta=objecta, objectb=objectb)
            o.save()
            objectcs.append(o)

    def check_union(self, model, Q1, Q2):
        filter = model.objects.filter
        self.assertEqual(set(filter(Q1) | filter(Q2)), set(filter(Q1 | Q2)))
        self.assertEqual(set(filter(Q2) | filter(Q1)), set(filter(Q1 | Q2)))

    def test_A_AB(self):
        Q1 = Q(name='two')
        Q2 = Q(objectb__name='deux')
        self.check_union(ObjectA, Q1, Q2)

    def test_A_AB2(self):
        Q1 = Q(name='two')
        Q2 = Q(objectb__name='deux', objectb__num=2)
        self.check_union(ObjectA, Q1, Q2)

    def test_AB_ACB(self):
        Q1 = Q(objectb__name='deux')
        Q2 = Q(objectc__objectb__name='deux')
        self.check_union(ObjectA, Q1, Q2)

    def test_BAB_BAC(self):
        Q1 = Q(objecta__objectb__name='deux')
        Q2 = Q(objecta__objectc__name='ein')
        self.check_union(ObjectB, Q1, Q2)

    def test_BAB_BACB(self):
        Q1 = Q(objecta__objectb__name='deux')
        Q2 = Q(objecta__objectc__objectb__name='trois')
        self.check_union(ObjectB, Q1, Q2)

    def test_BA_BCA__BAB_BAC_BCA(self):
        Q1 = Q(objecta__name='one', objectc__objecta__name='two')
        Q2 = Q(objecta__objectc__name='ein', objectc__objecta__name='three', objecta__objectb__name='trois')
        self.check_union(ObjectB, Q1, Q2)


class DefaultValuesInsertTest(TestCase):
    def test_no_extra_params(self):
        """
        Can create an instance of a model with only the PK field (#17056)."
        """
        DumbCategory.objects.create()


class ExcludeTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        f1 = Food.objects.create(name='apples')
        Food.objects.create(name='oranges')
        Eaten.objects.create(food=f1, meal='dinner')
        j1 = Job.objects.create(name='Manager')
        r1 = Responsibility.objects.create(description='Playing golf')
        j2 = Job.objects.create(name='Programmer')
        r2 = Responsibility.objects.create(description='Programming')
        JobResponsibilities.objects.create(job=j1, responsibility=r1)
        JobResponsibilities.objects.create(job=j2, responsibility=r2)

    def test_to_field(self):
        self.assertQuerysetEqual(
            Food.objects.exclude(eaten__meal='dinner'),
            ['<Food: oranges>'])
        self.assertQuerysetEqual(
            Job.objects.exclude(responsibilities__description='Playing golf'),
            ['<Job: Programmer>'])
        self.assertQuerysetEqual(
            Responsibility.objects.exclude(jobs__name='Manager'),
            ['<Responsibility: Programming>'])

    def test_ticket14511(self):
        alex = Person.objects.get_or_create(name='Alex')[0]
        jane = Person.objects.get_or_create(name='Jane')[0]


        oracle = Company.objects.get_or_create(name='Oracle')[0]