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,
)
        # parent objects
        self.assertQuerysetEqual(ObjectC.objects.exclude(childobjecta=self.oa), out_c)

        # QuerySet related object type checking shouldn't issue queries
        # (the querysets aren't evaluated here, hence zero queries) (#23266).
        with self.assertNumQueries(0):
            ObjectB.objects.filter(objecta__in=ObjectA.objects.all())

    def test_values_queryset_lookup(self):
        """
        #23396 - Ensure ValueQuerySets are not checked for compatibility with the lookup field
        """
        # Make sure the num and objecta field values match.
        ob = ObjectB.objects.get(name='ob')
        ob.num = ob.objecta.pk
        ob.save()
        pob = ObjectB.objects.get(name='pob')
        pob.num = pob.objecta.pk
        pob.save()
        self.assertQuerysetEqual(ObjectB.objects.filter(
            objecta__in=ObjectB.objects.all().values_list('num')
        ).order_by('pk'), ['<ObjectB: ob>', '<ObjectB: pob>'])


class Ticket14056Tests(TestCase):
    def test_ticket_14056(self):
        s1 = SharedConnection.objects.create(data='s1')
        s2 = SharedConnection.objects.create(data='s2')
        s3 = SharedConnection.objects.create(data='s3')
        PointerA.objects.create(connection=s2)
        expected_ordering = (
            [s1, s3, s2] if connection.features.nulls_order_largest
            else [s2, s1, s3]
        )
        self.assertSequenceEqual(SharedConnection.objects.order_by('-pointera__connection', 'pk'), expected_ordering)


class Ticket20955Tests(TestCase):
    def test_ticket_20955(self):
        jack = Staff.objects.create(name='jackstaff')
        jackstaff = StaffUser.objects.create(staff=jack)
        jill = Staff.objects.create(name='jillstaff')
        jillstaff = StaffUser.objects.create(staff=jill)
        task = Task.objects.create(creator=jackstaff, owner=jillstaff, title="task")
        task_get = Task.objects.get(pk=task.pk)
        # Load data so that assertNumQueries doesn't complain about the get
        # version's queries.
        task_get.creator.staffuser.staff
        task_get.owner.staffuser.staff
        qs = Task.objects.select_related(
            'creator__staffuser__staff', 'owner__staffuser__staff')
        self.assertEqual(str(qs.query).count(' JOIN '), 6)
        task_select_related = qs.get(pk=task.pk)
        with self.assertNumQueries(0):
            self.assertEqual(task_select_related.creator.staffuser.staff,
                             task_get.creator.staffuser.staff)
            self.assertEqual(task_select_related.owner.staffuser.staff,
                             task_get.owner.staffuser.staff)


class Ticket21203Tests(TestCase):
    def test_ticket_21203(self):
        p = Ticket21203Parent.objects.create(parent_bool=True)
        c = Ticket21203Child.objects.create(parent=p)
        qs = Ticket21203Child.objects.select_related('parent').defer('parent__created')
        self.assertSequenceEqual(qs, [c])
        self.assertIs(qs[0].parent.parent_bool, True)


class ValuesJoinPromotionTests(TestCase):
    def test_values_no_promotion_for_existing(self):
        qs = Node.objects.filter(parent__parent__isnull=False)
        self.assertIn(' INNER JOIN ', str(qs.query))
        qs = qs.values('parent__parent__id')
        self.assertIn(' INNER JOIN ', str(qs.query))
        # Make sure there is a left outer join without the filter.
        qs = Node.objects.values('parent__parent__id')
        self.assertIn(' LEFT OUTER JOIN ', str(qs.query))

    def test_non_nullable_fk_not_promoted(self):
        qs = ObjectB.objects.values('objecta__name')
        self.assertIn(' INNER JOIN ', str(qs.query))

    def test_ticket_21376(self):
        a = ObjectA.objects.create()
        ObjectC.objects.create(objecta=a)
        qs = ObjectC.objects.filter(
            Q(objecta=a) | Q(objectb__objecta=a),
        )
        qs = qs.filter(
            Q(objectb=1) | Q(objecta=a),
        )
        self.assertEqual(qs.count(), 1)
        tblname = connection.ops.quote_name(ObjectB._meta.db_table)
        self.assertIn(' LEFT OUTER JOIN %s' % tblname, str(qs.query))


class ForeignKeyToBaseExcludeTests(TestCase):
    def test_ticket_21787(self):
        sc1 = SpecialCategory.objects.create(special_name='sc1', name='sc1')
        sc2 = SpecialCategory.objects.create(special_name='sc2', name='sc2')
        sc3 = SpecialCategory.objects.create(special_name='sc3', name='sc3')
        c1 = CategoryItem.objects.create(category=sc1)
        CategoryItem.objects.create(category=sc2)
        self.assertSequenceEqual(SpecialCategory.objects.exclude(categoryitem__id=c1.pk).order_by('name'), [sc2, sc3])
        self.assertSequenceEqual(SpecialCategory.objects.filter(categoryitem__id=c1.pk), [sc1])


class ReverseM2MCustomPkTests(TestCase):
    def test_ticket_21879(self):
        cpt1 = CustomPkTag.objects.create(id='cpt1', tag='cpt1')
        cp1 = CustomPk.objects.create(name='cp1', extra='extra')
        cp1.custompktag_set.add(cpt1)
        self.assertSequenceEqual(CustomPk.objects.filter(custompktag=cpt1), [cp1])
        self.assertSequenceEqual(CustomPkTag.objects.filter(custom_pk=cp1), [cpt1])


class Ticket22429Tests(TestCase):
    def test_ticket_22429(self):
        sc1 = School.objects.create()

        st1 = Student.objects.create(school=sc1)