| 1 | from django.contrib.auth.models import User
|
|---|
| 2 | from django.db.models import F, Value
|
|---|
| 3 | from django.db.models.functions import Concat
|
|---|
| 4 | from django.db.transaction import atomic
|
|---|
| 5 | from django.test import TestCase
|
|---|
| 6 |
|
|---|
| 7 |
|
|---|
| 8 | class QuerySetTestCase(TestCase):
|
|---|
| 9 | @classmethod
|
|---|
| 10 | def setUpTestData(cls):
|
|---|
| 11 | super().setUpTestData()
|
|---|
| 12 | User.objects.create(
|
|---|
| 13 | pk=12, username="A", first_name="A", last_name="B", email="test@example.com"
|
|---|
| 14 | )
|
|---|
| 15 |
|
|---|
| 16 | def test_alias(self):
|
|---|
| 17 | id_ = (
|
|---|
| 18 | User.objects.values_list("pk")
|
|---|
| 19 | .alias(other=F("first_name"))
|
|---|
| 20 | .filter(other="A")
|
|---|
| 21 | )
|
|---|
| 22 | self.assertQuerySetEqual(id_, [(12,)])
|
|---|
| 23 |
|
|---|
| 24 | def test_select_for_update(self):
|
|---|
| 25 | qs = User.objects.select_for_update(of=("self",)).values_list(
|
|---|
| 26 | Concat(F("first_name"), Value(" "), F("last_name")), "email"
|
|---|
| 27 | )
|
|---|
| 28 | with atomic():
|
|---|
| 29 | values = (
|
|---|
| 30 | User.objects.select_for_update(of=("self",))
|
|---|
| 31 | .values_list(
|
|---|
| 32 | Concat(F("first_name"), Value(" "), F("last_name")), "email"
|
|---|
| 33 | )
|
|---|
| 34 | .get(pk=12)
|
|---|
| 35 | )
|
|---|
| 36 | self.assertTupleEqual(values, ("A B", "test@example.com"))
|
|---|