---
title: "Feidhmeanna Sonraí"
version: 6.0
locale: ga
source: https://docs.djangoproject.com/ga/6.0/ref/models/database-functions/
canonical: https://djangodocs.dev/ga/6.0/ref/models/database-functions/
---
# Feidhmeanna Sonraí

The classes documented below provide a way for users to use functions provided
by the underlying database as annotations, aggregations, or filters in Django.
Functions are also [expressions](/ga/6.0/ref/models/expressions/), so they can be
used and combined with other expressions like [aggregate functions](/ga/6.0/ref/models/querysets/#aggregation-functions). See the [`Func`](/ga/6.0/ref/models/expressions/#django.db.models.Func) documentation
for security considerations.

Beidh muid ag úsáid an tsamhail seo a leanas i samplaí de gach feidhm:

```
class Author(models.Model):
    name = models.CharField(max_length=50)
    age = models.PositiveIntegerField(null=True, blank=True)
    alias = models.CharField(max_length=50, null=True, blank=True)
    goes_by = models.CharField(max_length=50, null=True, blank=True)
```

De ghnáth ní mholaimid `Null=True` a cheadú do `Charfield` ós rud é go gceadaíonn sé seo dhá “luach folamh” a bheith ag an réimse, ach tá sé tábhachtach don sampla `Coalesce` thíos.

## Feidhmeanna comparáide agus tiontai

### `Cast`

#### `class Cast(expression, output_field)`

Cuireann iallach ar an gcineál torthaí `expression` mar an ceann ó `output_field`.

Sampla úsáide:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cast
>>> Author.objects.create(age=25, name="Margaret Smith")
>>> author = Author.objects.annotate(
...     age_as_float=Cast("age", output_field=FloatField()),
... ).get()
>>> print(author.age_as_float)
25.0
```

### `Coalesce`

#### `class Coalesce(*expressions, **extra)`

Glacann sé le liosta de dhá ainm nó abairt réimse ar a laghad agus tugann sé an chéad luach neamh-niall ar ais (tabhair faoi deara nach meastar gur luach neamh-mheas teaghrán folamh). Caithfidh gach argóint a bheith de chineál céanna, mar sin beidh earráid bunachar sonraí mar thoradh ar théacs agus uimhreacha a mheascadh.

Samplaí úsáide:

```pycon
>>> # Get a screen name from least to most public
>>> from django.db.models import Sum
>>> from django.db.models.functions import Coalesce
>>> Author.objects.create(name="Margaret Smith", goes_by="Maggie")
>>> author = Author.objects.annotate(screen_name=Coalesce("alias", "goes_by", "name")).get()
>>> print(author.screen_name)
Maggie

>>> # Prevent an aggregate Sum() from returning None
>>> # The aggregate default argument uses Coalesce() under the hood.
>>> aggregated = Author.objects.aggregate(
...     combined_age=Sum("age"),
...     combined_age_default=Sum("age", default=0),
...     combined_age_coalesce=Coalesce(Sum("age"), 0),
... )
>>> print(aggregated["combined_age"])
None
>>> print(aggregated["combined_age_default"])
0
>>> print(aggregated["combined_age_coalesce"])
0
```

> **Warning**
>
> Féadfar luach Python a chuirtear chuig Coalesce\` ar MySQL a thiontú go cineál mícheart mura gcaitheadh go sainráite chuig an gcineál ceart bunachar sonraí:
>
> ```pycon
> >>> from django.db.models import DateTimeField
> >>> from django.db.models.functions import Cast, Coalesce
> >>> from django.utils import timezone
> >>> now = timezone.now()
> >>> Coalesce("updated", Cast(now, DateTimeField()))
> ```

### `Collate`

#### `class Collate(expression, collation)`

Tógann sé abairt agus ainm comhlánaithe le fiosrú ina choinne.

Mar shampla, chun cás-neamhíogair a scagadh i SQLite:

```pycon
>>> Author.objects.filter(name=Collate(Value("john"), "nocase"))
<QuerySet [<Author: John>, <Author: john>]>
```

Is féidir é a úsáid freisin agus tú ag ordú, mar shampla le PostgreSQL:

```pycon
>>> Author.objects.order_by(Collate("name", "et-x-icu"))
<QuerySet [<Author: Ursula>, <Author: Veronika>, <Author: Ülle>]>
```

### An Mhór \`\`

#### `class Greatest(*expressions, **extra)`

Glacann sé le liosta de dhá ainm nó abairt réimse ar a laghad agus tugann sé an luach is mó ar ais. Caithfidh gach argóint a bheith de chineál céanna, mar sin beidh earráid bunachar sonraí mar thoradh ar théacs agus uimhreacha a mheascadh.

Sampla úsáide:

```
class Blog(models.Model):
    body = models.TextField()
    modified = models.DateTimeField(auto_now=True)

class Comment(models.Model):
    body = models.TextField()
    modified = models.DateTimeField(auto_now=True)
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
```

```pycon
>>> from django.db.models.functions import Greatest
>>> blog = Blog.objects.create(body="Greatest is the best.")
>>> comment = Comment.objects.create(body="No, Least is better.", blog=blog)
>>> comments = Comment.objects.annotate(last_updated=Greatest("modified", "blog__modified"))
>>> annotated_comment = comments.get()
```

Beidh `annotated_comment.last_updated` an ceann is déanaí de blog.modified\` agus `comment.modified`.

> **Warning**
>
> Athraíonn iompar `Greatest` nuair a bhféadfadh abairt amháin nó níos mó a bheith `null` idir bunachair sonraí:
>
> - PostgreSQL: Tabharfaidh `Greatest` an abairt neamh-null is mó ar ais, nó `null` má tá null\` gach abairt `null`.
> - SQLite, Oracle, agus MySQL: Má tá aon abairt `null`, fillfidh `` `Greatest `` `null`.
>
> Is féidir aithris a dhéanamh ar iompar PostgreSQL ag baint úsáide as `Coalesce` má tá íosluach ciallmhar ar eolas agat le soláthar mar réamhshocraithe.

### `Is Leas`

#### `class Least(*expressions, **extra)`

Glacann sé le liosta de dhá ainm nó abairt réimse ar a laghad agus tugann sé an luach is lú ar ais. Caithfidh gach argóint a bheith de chineál céanna, mar sin beidh earráid bunachar sonraí mar thoradh ar théacs agus uimhreacha a mheascadh.

> **Warning**
>
> Athraíonn iompar ```Is Leas` nuair a bhféadfadh léiriú amháin nó níos mó a bheith ``null``` idir bunachair sonraí:
>
> - PostgreSQL: Tabharfaidh `Is leith` an abairt neamh-null is lú ar ais, nó `null` má tá null\` na nathanna go léir `null`.
> - SQLite, Oracle, agus MySQL: Má tá aon abairt `null`, fillfidh ```` `Is Leas` ```null ````.
>
> Is féidir aithris a dhéanamh ar iompar PostgreSQL ag baint úsáide as `Coalesce` má tá uasluach ciallmhar ar eolas agat le soláthar mar réamhshocraithe.

### `Nullif`

#### `class NullIf(expression1, expression2)`

Glacann sé le dhá abairt agus filleann sé `None` má tá siad comhionann, ar shlí eile filleann sé `expression1`.

> **Rabhadh ar Oracle**
>
> Mar gheall ar an:ref: Coinbhinsiún Oracle \<oracle-null-empty-strings\>, filleann an fheidhm seo an teaghrán folamh in ionad `None` nuair a bhíonn na nathanna de chineál:class: ~django.db.models.charfield.
>
> Tá cosc ar ```Luach (Níl) ``a chur chuig `expression1``` ar Oracle ós rud é nach nglacann Oracle le `NULL` mar an chéad argóint.

## Feidhmeanna dáta

Beidh muid ag úsáid an tsamhail seo a leanas i samplaí de gach feidhm:

```
class Experiment(models.Model):
    start_datetime = models.DateTimeField()
    start_date = models.DateField(null=True, blank=True)
    start_time = models.TimeField(null=True, blank=True)
    end_datetime = models.DateTimeField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    end_time = models.TimeField(null=True, blank=True)
```

### Sliocht \`\`

#### `class Extract(expression, lookup_name=None, tzinfo=None, **extra)`

Baineann comhpháirt de dháta mar uimhir.

Glacann sé `expression` a léiríonn `DateField`, DateTimefield\`, Timefield\`, nó `Durationfield` agus `lookup_name`, agus filleann sé an chuid den dáta dá dtagraítear `lookup_name` mar ```limistéar. De ghnáth úsáideann Django feidhm sliocht na mbunachar sonraí, mar sin féadfaidh tú aon ``lookup_name``` a úsáid a thacaíonn do bhunachar sonraí. Is féidir fo-aicme tzinfo\`, a sholáthraíonn u:mod: zoneinfo de ghnáth, a chur ar aghaidh chun luach a bhaint i gcrios ama ar leith.

I bhfianaise an dáta ```2015-06-15 23:30:01.000 321+ 00:00 ``, filleann an ``lookup_name``` ionsuite:

- “bliain”: 2015
- “Iso\_bliain”: 2015
- “ráithe”: 2
- “mhí”: 6
- “lá”: 15
- “seachtain”: 25
- “Lá na seachtaine”: 2
- “Iso\_lá seachtaine”: 1
- “uair an chloig”: 23
- “nóiméad”: 30
- “an dara”: 1

Má tá crios ama difriúil mar `Astráil/Melbourne` gníomhach i Django, ansin déantar an dáta-am a thiontú go dtí an crios ama sula mbaintear an luach. Is é an fhritháireamh crios ama do Melbourne sa dáta sampla thuas ná + 10:00. Beidh na luachanna a chuirtear ar ais nuair a bhíonn an crios ama seo gníomhach mar an gcéanna agus thuas ach amháin:

- “lá”: 16
- “Lá na seachtaine”: 3
- “Lá seachtaine ”: 2
- “uair an chloig”: 9

> **Luachanna seachtain_laeth**
>
> Ríomhtar an `week_day` lookup\_type\` go difriúil ó fhormhór na mbunachair sonraí agus ó fheidhmeanna caighdeánacha Python. Tabharfaidh an fheidhm seo `1` ar ais don Domhnach, `2` don Luain, trí `7` don Dé Sathairn.
>
> Is é an ríomh coibhéiseach i Python:
>
> ```pycon
> >>> from datetime import datetime
> >>> dt = datetime(2015, 6, 15)
> >>> (dt.isoweekday() % 7) + 1
> 2
> ```

> **Luachanna seachtain**
>
> \< <https://en.wikipedia.org/wiki/ISO-8601>\>Ríomhtar an `seachtaine` lookup\_type\` bunaithe ar [ISO-8601](#iso-8601), ie, tosaíonn seachtain ar Dé Luain. Is í an chéad seachtain de bhliain an ceann ina bhfuil an chéad Déardaoin na bliana, i.e. tá tromlach (ceithre nó níos mó) dá laethanta sa bhliain ag an gcéad seachtain. Tá an luach a thugtar ar ais sa raon 1 go 52 nó 53.

Tá fo-aicme comhfhreagrach `` `Extract `` (liostaithe thíos) ag gach `lookup_name` thuas ar chóir a úsáid de ghnáth in ionad an choibhéis níos fhíorúla, m.sh. bain úsáid as ExtractYear (...) seachas Extract (..., lookup\_name = 'year') .

Sampla úsáide:

```pycon
>>> from datetime import datetime
>>> from django.db.models.functions import Extract
>>> start = datetime(2015, 6, 15)
>>> end = datetime(2015, 7, 2)
>>> Experiment.objects.create(
...     start_datetime=start, start_date=start.date(), end_datetime=end, end_date=end.date()
... )
>>> # Add the experiment start year as a field in the QuerySet.
>>> experiment = Experiment.objects.annotate(
...     start_year=Extract("start_datetime", "year")
... ).get()
>>> experiment.start_year
2015
>>> # How many experiments completed in the same year in which they started?
>>> Experiment.objects.filter(start_datetime__year=Extract("end_datetime", "year")).count()
1
```

#### Sleachta Datefield \`\`

#### `class ExtractYear(expression, tzinfo=None, **extra)`

#### `lookup_name = 'year'`

#### `class ExtractIsoYear(expression, tzinfo=None, **extra)`

Tugann an bhliain uimhrithe seachtaine ISO-8601 ar ais.

#### `lookup_name = 'iso_year'`

#### `class ExtractMonth(expression, tzinfo=None, **extra)`

#### `lookup_name = 'month'`

#### `class ExtractDay(expression, tzinfo=None, **extra)`

#### `lookup_name = 'day'`

#### `class ExtractWeekDay(expression, tzinfo=None, **extra)`

#### `lookup_name = 'week_day'`

#### `class ExtractIsoWeekDay(expression, tzinfo=None, **extra)`

Filleann sé lá na seachtaine ISO-8601 agus lá 1 é Luan agus lá 7 é Dé Domhnaigh.

#### `lookup_name = 'iso_week_day'`

#### `class ExtractWeek(expression, tzinfo=None, **extra)`

#### `lookup_name = 'week'`

#### `class ExtractQuarter(expression, tzinfo=None, **extra)`

#### `lookup_name = 'quarter'`

Tá siad seo coibhéiseach go loighciúil le ```Extract ('date_field', lookup_name) ``. Is é gach rang freisin ``Transform``` atá cláraithe ar `DateField` agus `DateTimeField` mar ```__ (lookup_name) ``, m.sh. ``__year```.

Ós rud é nach bhfuil comhpháirt ama ag `Datefield`, ní féidir ach fo-aicmí ```Extract ``a dhéileálann le dáta-chodanna a úsáid le ``Datefield```:

```pycon
>>> from datetime import UTC, datetime
>>> from django.db.models.functions import (
...     ExtractDay,
...     ExtractMonth,
...     ExtractQuarter,
...     ExtractWeek,
...     ExtractIsoWeekDay,
...     ExtractWeekDay,
...     ExtractIsoYear,
...     ExtractYear,
... )
>>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=UTC)
>>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=UTC)
>>> Experiment.objects.create(
...     start_datetime=start_2015,
...     start_date=start_2015.date(),
...     end_datetime=end_2015,
...     end_date=end_2015.date(),
... )
>>> Experiment.objects.annotate(
...     year=ExtractYear("start_date"),
...     isoyear=ExtractIsoYear("start_date"),
...     quarter=ExtractQuarter("start_date"),
...     month=ExtractMonth("start_date"),
...     week=ExtractWeek("start_date"),
...     day=ExtractDay("start_date"),
...     weekday=ExtractWeekDay("start_date"),
...     isoweekday=ExtractIsoWeekDay("start_date"),
... ).values(
...     "year",
...     "isoyear",
...     "quarter",
...     "month",
...     "week",
...     "day",
...     "weekday",
...     "isoweekday",
... ).get(
...     end_date__year=ExtractYear("start_date")
... )
{'year': 2015, 'isoyear': 2015, 'quarter': 2, 'month': 6, 'week': 25,
 'day': 15, 'weekday': 2, 'isoweekday': 1}
```

#### Sleachta `DateTimefield`

Chomh maith leis an méid seo a leanas, féadfar gach sliocht do ```DateField ``atá liostaithe thuas a úsáid freisin ar ``DateTimefield```s.

#### `class ExtractHour(expression, tzinfo=None, **extra)`

#### `lookup_name = 'hour'`

#### `class ExtractMinute(expression, tzinfo=None, **extra)`

#### `lookup_name = 'minute'`

#### `class ExtractSecond(expression, tzinfo=None, **extra)`

#### `lookup_name = 'second'`

Tá siad seo coibhéiseach go loighciúil le ```Extract ('datetime_field', lookup_name) ``. Is `Transform``` é gach rang freisin atá cláraithe ar `DateTimeField` mar ```__ (lookup_name) ``, m.sh. ``__minute```.

Samplaí `DateTimeField`:

```pycon
>>> from datetime import UTC, datetime
>>> from django.db.models.functions import (
...     ExtractDay,
...     ExtractHour,
...     ExtractMinute,
...     ExtractMonth,
...     ExtractQuarter,
...     ExtractSecond,
...     ExtractWeek,
...     ExtractIsoWeekDay,
...     ExtractWeekDay,
...     ExtractIsoYear,
...     ExtractYear,
... )
>>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=UTC)
>>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=UTC)
>>> Experiment.objects.create(
...     start_datetime=start_2015,
...     start_date=start_2015.date(),
...     end_datetime=end_2015,
...     end_date=end_2015.date(),
... )
>>> Experiment.objects.annotate(
...     year=ExtractYear("start_datetime"),
...     isoyear=ExtractIsoYear("start_datetime"),
...     quarter=ExtractQuarter("start_datetime"),
...     month=ExtractMonth("start_datetime"),
...     week=ExtractWeek("start_datetime"),
...     day=ExtractDay("start_datetime"),
...     weekday=ExtractWeekDay("start_datetime"),
...     isoweekday=ExtractIsoWeekDay("start_datetime"),
...     hour=ExtractHour("start_datetime"),
...     minute=ExtractMinute("start_datetime"),
...     second=ExtractSecond("start_datetime"),
... ).values(
...     "year",
...     "isoyear",
...     "month",
...     "week",
...     "day",
...     "weekday",
...     "isoweekday",
...     "hour",
...     "minute",
...     "second",
... ).get(
...     end_datetime__year=ExtractYear("start_datetime")
... )
{'year': 2015, 'isoyear': 2015, 'quarter': 2, 'month': 6, 'week': 25,
 'day': 15, 'weekday': 2, 'isoweekday': 1, 'hour': 23, 'minute': 30,
 'second': 1}
```

Nuair: Setting: USE\_TZ `True` ansin stóráiltear dáta-amanna sa bhunachar sonraí i UTC. Má tá crios ama difriúil gníomhach i Django, déantar an dáta-am a thiontú go dtí an crios ama sin sula mbaintear an luach. Athraíonn an sampla thíos go crios ama Melbourne (UTC + 10:00), a athraíonn na luachanna lae, lá na seachtaine agus na huaire a chuirtear ar ais:

```pycon
>>> from django.utils import timezone
>>> import zoneinfo
>>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")  # UTC+10:00
>>> with timezone.override(melb):
...     Experiment.objects.annotate(
...         day=ExtractDay("start_datetime"),
...         weekday=ExtractWeekDay("start_datetime"),
...         isoweekday=ExtractIsoWeekDay("start_datetime"),
...         hour=ExtractHour("start_datetime"),
...     ).values("day", "weekday", "isoweekday", "hour").get(
...         end_datetime__year=ExtractYear("start_datetime"),
...     )
...
{'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}
```

Iompraíonn an crios ama a chur go sainráite chuig an bhfeidhm `Extract` ar an mbealach céanna, agus tugann sé tosaíocht thar chrios ama gníomhach:

```pycon
>>> import zoneinfo
>>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
>>> Experiment.objects.annotate(
...     day=ExtractDay("start_datetime", tzinfo=melb),
...     weekday=ExtractWeekDay("start_datetime", tzinfo=melb),
...     isoweekday=ExtractIsoWeekDay("start_datetime", tzinfo=melb),
...     hour=ExtractHour("start_datetime", tzinfo=melb),
... ).values("day", "weekday", "isoweekday", "hour").get(
...     end_datetime__year=ExtractYear("start_datetime"),
... )
{'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}
```

### Anois \`\`

#### `class Now`

Filleann sé dáta agus am reatha an fhreastalaí bunachar sonraí nuair a chuirtear an ceist i bhfeidhm, de ghnáth ag baint úsáide as an SQL CURRENT\_TIMESTAMP\`.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Now
>>> Article.objects.filter(published__lte=Now())
<QuerySet [<Article: How to Django>]>
```

> **Creithnithe PostgreSQL**
>
> Ar PostgreSQL, filleann an SQL `CURRENT_TIMESTAMP` an t-am a thosaigh an t-idirbheart reatha. Dá bhrí sin le haghaidh comhoiriúnacht tras-bhunachar sonraí, úsáideann ````Now () ```STATEMENT_TIMESTAMP```` ina ionad. Má theastaíonn an stampa ama idirbheart uait, bain úsáid as: class: django.contrib.postgres.functions.TransactionNow.

> **Oracle**
>
> Ar Oracle, úsáidtear an SQL `LOCALTIMESTAMP` chun saincheisteanna a sheachaint le réitigh `CURRENT_TIMESTAMP` go DateTimeField\`.

### `Trunc`

#### `class Trunc(expression, kind, output_field=None, tzinfo=None, **extra)`

Déanann sé dáta a ghearradh suas go dtí comhpháirt shuntasach.

Nuair nach bhfuil cúram ort ach má tharla rud éigin i mbliain, uair an chloig nó lá áirithe, ach ní an dara ceart, ansin is féidir le ```Trunc` (agus a fho-aicmí) a bheith úsáideach chun do chuid sonraí a scagadh nó a chomhiomlánú. Mar shampla, is féidir leat ``Trunc``` a úsáid chun líon na ndíolacháin in aghaidh an lae a ríomh.

Glacann `Trunc` léirithe\` amháin, a léiríonn `DataField`, Timefield\`, nó `DateTimeField`, `cine` a léiríonn cuid dáta nó ama, agus `output_field` arb é `DateTimeField ()`, TimeField () \`, nó\`\` Timefield () ```, nó ``Timefield ()```, ``, `Timefield ()``, nó ``` `“Dáta Field () ``. Tugann sé dáta-am, dáta nó am ar ais ag brath ar ``output_field ```, le réimsí suas le cineál socraithe dá luach íosta. Má fhágtar `output_field`, réamhshocróidh sé go `output_field` de expression\`. Is féidir fo-aicme tzinfo\`, a sholáthraíonn u:mod: zoneinfo de ghnáth, a chur ar aghaidh chun luach a ghearradh i gcrios ama ar leith.

I bhfianaise an dáta ```2015-06-15 14:30:50.000 321+ 00:00 ``, filleann an ``cine``` ionsuite:

- “bliain”: 2015-01-01 00:00:00 + 00:00
- “ráithe”: 2015-04-01 00:00:00 + 00:00
- “mhí”: 2015-06-01 00:00:00 + 00:00
- “Seachtain”: 2015-06-15 00:00:00 + 00:00
- “lá”: 2015-06-15 00:00:00 + 00:00
- “uair an chloig”: 2015-06-15 14:00:00 + 00:00
- “nóiméad”: 2015-06-15 14:30:00 + 00:00
- “an dara”: 2015-06-15 14:30:50 + 00:00

Má tá crios ama difriúil mar `Astráil/Melbourne` gníomhach i Django, ansin déantar an dáta-am a thiontú go dtí an crios ama nua sula ndéantar an luach a ghearradh. Is é an fhritháireamh crios ama do Melbourne sa dáta sampla thuas ná + 10:00. Is iad na luachanna a thugtar ar ais nuair a bheidh an crios ama seo gníomhach ná

- “bliain”: 2015-01-01 00:00:00 + 11:00
- “ráithe”: 2015-04-01 00:00:00 + 10:00
- “mhí”: 2015-06-01 00:00:00 + 10:00
- “Seachtain”: 2015-06-16 00:00:00 + 10:00
- “lá”: 2015-06-16 00:00:00 + 10:00
- “uair an chloig”: 2015-06-16 00:00:00 + 10:00
- “nóiméad”: 2015-06-16 00:30:00 + 10:00
- “an dara”: 2015-06-16 00:30:50 + 10:00

Tá fritháireamh + 11:00 ag an mbliain toisc gur aistrigh an toradh go dtí am sábhála solais an lae.

Tá fo-aicme comhfhreagrach `` `Trunc `` (liostaithe thíos) ag gach cineál\` thuas ar chóir a úsáid de ghnáth in ionad an choibhéis is eolaí, m.sh. bain úsáid as ```TruncYear (...) ``seachas ``Trunc (..., cine='bliain')```.

Sainmhínítear na fo-aicmí go léir mar athruithe, ach níl siad cláraithe le réimsí ar bith, toisc go bhfuil na fo-aicmí Eisceacht' in áirithe cheana féin na hainmneacha cuardaigh.

Sampla úsáide:

```pycon
>>> from datetime import datetime
>>> from django.db.models import Count, DateTimeField
>>> from django.db.models.functions import Trunc
>>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321))
>>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 40, 2, 123))
>>> Experiment.objects.create(start_datetime=datetime(2015, 12, 25, 10, 5, 27, 999))
>>> experiments_per_day = (
...     Experiment.objects.annotate(
...         start_day=Trunc("start_datetime", "day", output_field=DateTimeField())
...     )
...     .values("start_day")
...     .annotate(experiments=Count("id"))
... )
>>> for exp in experiments_per_day:
...     print(exp["start_day"], exp["experiments"])
...
2015-06-15 00:00:00 2
2015-12-25 00:00:00 1
>>> experiments = Experiment.objects.annotate(
...     start_day=Trunc("start_datetime", "day", output_field=DateTimeField())
... ).filter(start_day=datetime(2015, 6, 15))
>>> for exp in experiments:
...     print(exp.start_datetime)
...
2015-06-15 14:30:50.000321
2015-06-15 14:40:02.000123
```

#### `Dáta Field` truncation

#### `class TruncYear(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'year'`

#### `class TruncMonth(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'month'`

#### `class TruncWeek(expression, output_field=None, tzinfo=None, **extra)`

Cuireann sé go meán oíche Dé Luain na seachtaine.

#### `kind = 'week'`

#### `class TruncQuarter(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'quarter'`

Tá siad seo coibhéiseach go loighciúil le ```Trunc ('date_field', cineál) ``. Déanann siad gach cuid den dáta a ghearradh suas go dtí ``cineál`, rud a cheadaíonn dátaí a ghrúpáil nó a scagadh gan níos lú cruinneas. Is féidir le ``expression``` output\_field\` de `DateField` nó `DateTimefield` a bheith aige.

Ós rud é nach bhfuil comhpháirt ama ag `Datefield`, ní féidir ach fo-aicmí `Trunc` a dhéileálann le dáta-chodanna a úsáid le `Datefield`:

```pycon
>>> from datetime import UTC, datetime
>>> from django.db.models import Count
>>> from django.db.models.functions import TruncMonth, TruncYear
>>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=UTC)
>>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=UTC)
>>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=UTC)
>>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
>>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())
>>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())
>>> experiments_per_year = (
...     Experiment.objects.annotate(year=TruncYear("start_date"))
...     .values("year")
...     .annotate(experiments=Count("id"))
... )
>>> for exp in experiments_per_year:
...     print(exp["year"], exp["experiments"])
...
2014-01-01 1
2015-01-01 2

>>> import zoneinfo
>>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
>>> experiments_per_month = (
...     Experiment.objects.annotate(month=TruncMonth("start_datetime", tzinfo=melb))
...     .values("month")
...     .annotate(experiments=Count("id"))
... )
>>> for exp in experiments_per_month:
...     print(exp["month"], exp["experiments"])
...
2015-06-01 00:00:00+10:00 1
2016-01-01 00:00:00+11:00 1
2014-06-01 00:00:00+10:00 1
```

#### `DateTimeField` truncation

#### `class TruncDate(expression, tzinfo=None, **extra)`

#### `lookup_name = 'date'`

#### `output_field = DateField()`

Caitheann `TruncDate` sainráite\` go dáta seachas an fheidhm truncate SQL ionsuite a úsáid. Tá sé cláraithe freisin mar chlaochlú ar `DateTimeField` mar \_\_date .

#### `class TruncTime(expression, tzinfo=None, **extra)`

#### `lookup_name = 'time'`

#### `output_field = TimeField()`

Caitheann `TruncTime` léiriú \`\`go dtí am seachas an fheidhm truncate SQL ionsuite a úsáid. Tá sé cláraithe freisin mar chlaochlú ar \`\`DateTimeField\` mar `__time`.

#### `class TruncDay(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'day'`

#### `class TruncHour(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'hour'`

#### `class TruncMinute(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'minute'`

#### `class TruncSecond(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'second'`

Tá siad seo coibhéiseach go loighciúil le ```Trunc ('datetime_field', cineál) ``. Déanann siad gach cuid den dáta a ghearradh suas go “cineál” agus ceadaíonn siad dáta a ghrúpáil nó a scagadh le níos lú cruinneas. Caithfidh ``output_field``` de DateTimeField\` a bheith ag `expression`.

Sampla úsáide:

```pycon
>>> from datetime import UTC, date, datetime
>>> from django.db.models import Count
>>> from django.db.models.functions import (
...     TruncDate,
...     TruncDay,
...     TruncHour,
...     TruncMinute,
...     TruncSecond,
... )
>>> import zoneinfo
>>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=UTC)
>>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
>>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
>>> Experiment.objects.annotate(
...     date=TruncDate("start_datetime"),
...     day=TruncDay("start_datetime", tzinfo=melb),
...     hour=TruncHour("start_datetime", tzinfo=melb),
...     minute=TruncMinute("start_datetime"),
...     second=TruncSecond("start_datetime"),
... ).values("date", "day", "hour", "minute", "second").get()
{'date': datetime.date(2014, 6, 15),
 'day': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=zoneinfo.ZoneInfo('Australia/Melbourne')),
 'hour': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=zoneinfo.ZoneInfo('Australia/Melbourne')),
 'minute': 'minute': datetime.datetime(2014, 6, 15, 14, 30, tzinfo=UTC),
 'second': datetime.datetime(2014, 6, 15, 14, 30, 50, tzinfo=UTC)
}
```

#### `Aimréimhseach` curcú

#### `class TruncHour(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'hour'`

#### `class TruncMinute(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'minute'`

#### `class TruncSecond(expression, output_field=None, tzinfo=None, **extra)`

#### `kind = 'second'`

Tá siad seo coibhéiseach go loighciúil le ```Trunc ('time_field', cineál) ``. Déanann siad gach cuid den am a ghearradh suas go dtí “cineál” a cheadaíonn amanna grúpála nó scagtha le níos lú cruinneas. Is féidir le ``expression``` output\_field\` de `Timfield` nó `DateTimefield` a bheith aige.

Ós rud é nach bhfuil comhpháirt dáta ag `Timfield`, ní féidir ach fo-aicmí `Trunc` a dhéileálann le páirteanna ama a úsáid le `Timfield`:

```pycon
>>> from datetime import UTC, datetime
>>> from django.db.models import Count, TimeField
>>> from django.db.models.functions import TruncHour
>>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=UTC)
>>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=UTC)
>>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=UTC)
>>> Experiment.objects.create(start_datetime=start1, start_time=start1.time())
>>> Experiment.objects.create(start_datetime=start2, start_time=start2.time())
>>> Experiment.objects.create(start_datetime=start3, start_time=start3.time())
>>> experiments_per_hour = (
...     Experiment.objects.annotate(
...         hour=TruncHour("start_datetime", output_field=TimeField()),
...     )
...     .values("hour")
...     .annotate(experiments=Count("id"))
... )
>>> for exp in experiments_per_hour:
...     print(exp["hour"], exp["experiments"])
...
14:00:00 2
17:00:00 1

>>> import zoneinfo
>>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
>>> experiments_per_hour = (
...     Experiment.objects.annotate(
...         hour=TruncHour("start_datetime", tzinfo=melb),
...     )
...     .values("hour")
...     .annotate(experiments=Count("id"))
... )
>>> for exp in experiments_per_hour:
...     print(exp["hour"], exp["experiments"])
...
2014-06-16 00:00:00+10:00 2
2016-01-01 04:00:00+11:00 1
```

## JSON Functions

### `JSONArray`

> **New in Django 5.2**

#### `class JSONArray(*expressions)`

Accepts a list of field names or expressions and returns a JSON array
containing those values.

Sampla úsáide:

```pycon
>>> from django.db.models import F
>>> from django.db.models.functions import JSONArray, Lower
>>> Author.objects.create(name="Margaret Smith", alias="msmith", age=25)
>>> author = Author.objects.annotate(
...     json_array=JSONArray(
...         Lower("name"),
...         "alias",
...         F("age") * 2,
...     )
... ).get()
>>> author.json_array
['margaret smith', 'msmith', 50]
```

### `JSONObject`

#### `class JSONObject(**fields)`

Tógann sé liosta de phéirí luacha eochair agus filleann sé réad JSON ina bhfuil na péirí sin ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models import F
>>> from django.db.models.functions import JSONObject, Lower
>>> Author.objects.create(name="Margaret Smith", alias="msmith", age=25)
>>> author = Author.objects.annotate(
...     json_object=JSONObject(
...         name=Lower("name"),
...         alias="alias",
...         age=F("age") * 2,
...     )
... ).get()
>>> author.json_object
{'name': 'margaret smith', 'alias': 'msmith', 'age': 50}
```

## Feidhmeanna Mate

Beidh muid ag úsáid an tsamhail seo a leanas i samplaí feidhme matamaitice:

```
class Vector(models.Model):
    x = models.FloatField()
    y = models.FloatField()
```

### `Abs`

#### `class Abs(expression, **extra)`

Tugann luach iomlán réimse nó léirithe uimhriúil ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Abs
>>> Vector.objects.create(x=-0.5, y=1.1)
>>> vector = Vector.objects.annotate(x_abs=Abs("x"), y_abs=Abs("y")).get()
>>> vector.x_abs, vector.y_abs
(0.5, 1.1)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Abs
>>> FloatField.register_lookup(Abs)
>>> # Get vectors inside the unit cube
>>> vectors = Vector.objects.filter(x__abs__lt=1, y__abs__lt=1)
```

### Acos \`\`

#### `class ACos(expression, **extra)`

Tugann sé arcosine réimse nó léirithe uimhriúil ar ais. Caithfidh an luach abairt a bheith laistigh den raon -1 go 1.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import ACos
>>> Vector.objects.create(x=0.5, y=-0.9)
>>> vector = Vector.objects.annotate(x_acos=ACos("x"), y_acos=ACos("y")).get()
>>> vector.x_acos, vector.y_acos
(1.0471975511965979, 2.6905658417935308)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import ACos
>>> FloatField.register_lookup(ACos)
>>> # Get vectors whose arccosine is less than 1
>>> vectors = Vector.objects.filter(x__acos__lt=1, y__acos__lt=1)
```

### `Asin`

#### `class ASin(expression, **extra)`

Tugann sé arcsine réimse nó léirithe uimhriúil ar ais. Caithfidh an luach abairt a bheith sa raon -1 go 1.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import ASin
>>> Vector.objects.create(x=0, y=1)
>>> vector = Vector.objects.annotate(x_asin=ASin("x"), y_asin=ASin("y")).get()
>>> vector.x_asin, vector.y_asin
(0.0, 1.5707963267948966)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import ASin
>>> FloatField.register_lookup(ASin)
>>> # Get vectors whose arcsine is less than 1
>>> vectors = Vector.objects.filter(x__asin__lt=1, y__asin__lt=1)
```

### `Atan`

#### `class ATan(expression, **extra)`

Filleann sé arctangent réimse nó léirithe uimhriúil.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import ATan
>>> Vector.objects.create(x=3.12, y=6.987)
>>> vector = Vector.objects.annotate(x_atan=ATan("x"), y_atan=ATan("y")).get()
>>> vector.x_atan, vector.y_atan
(1.2606282660069106, 1.428638798133829)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import ATan
>>> FloatField.register_lookup(ATan)
>>> # Get vectors whose arctangent is less than 2
>>> vectors = Vector.objects.filter(x__atan__lt=2, y__atan__lt=2)
```

### `Atan2`

#### `class ATan2(expression1, expression2, **extra)`

Tugann sé an arctangent de `expression1/expression2` ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import ATan2
>>> Vector.objects.create(x=2.5, y=1.9)
>>> vector = Vector.objects.annotate(atan2=ATan2("x", "y")).get()
>>> vector.atan2
0.9209258773829491
```

### `Uasteorain`

#### `class Ceil(expression, **extra)`

Filleann sé an sláimhir is lú níos mó ná réimse uimhriúil nó léiriú uimhriúil.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Ceil
>>> Vector.objects.create(x=3.12, y=7.0)
>>> vector = Vector.objects.annotate(x_ceil=Ceil("x"), y_ceil=Ceil("y")).get()
>>> vector.x_ceil, vector.y_ceil
(4.0, 7.0)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Ceil
>>> FloatField.register_lookup(Ceil)
>>> # Get vectors whose ceil is less than 10
>>> vectors = Vector.objects.filter(x__ceil__lt=10, y__ceil__lt=10)
```

### `Cos`

#### `class Cos(expression, **extra)`

Tugann sé cosine réimse nó léirithe uimhriúil ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Cos
>>> Vector.objects.create(x=-8.0, y=3.1415926)
>>> vector = Vector.objects.annotate(x_cos=Cos("x"), y_cos=Cos("y")).get()
>>> vector.x_cos, vector.y_cos
(-0.14550003380861354, -0.9999999999999986)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cos
>>> FloatField.register_lookup(Cos)
>>> # Get vectors whose cosine is less than 0.5
>>> vectors = Vector.objects.filter(x__cos__lt=0.5, y__cos__lt=0.5)
```

### `Cot`

#### `class Cot(expression, **extra)`

Tugann sé cotangent réimse nó léirithe uimhriúil ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Cot
>>> Vector.objects.create(x=12.0, y=1.0)
>>> vector = Vector.objects.annotate(x_cot=Cot("x"), y_cot=Cot("y")).get()
>>> vector.x_cot, vector.y_cot
(-1.5726734063976826, 0.642092615934331)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cot
>>> FloatField.register_lookup(Cot)
>>> # Get vectors whose cotangent is less than 1
>>> vectors = Vector.objects.filter(x__cot__lt=1, y__cot__lt=1)
```

### `Céime`

#### `class Degrees(expression, **extra)`

Athraíonn sé réimse nó léiriú uimhriúil ó radáin go céimeanna.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Degrees
>>> Vector.objects.create(x=-1.57, y=3.14)
>>> vector = Vector.objects.annotate(x_d=Degrees("x"), y_d=Degrees("y")).get()
>>> vector.x_d, vector.y_d
(-89.95437383553924, 179.9087476710785)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Degrees
>>> FloatField.register_lookup(Degrees)
>>> # Get vectors whose degrees are less than 360
>>> vectors = Vector.objects.filter(x__degrees__lt=360, y__degrees__lt=360)
```

### `Exp`

#### `class Exp(expression, **extra)`

Tugann sé luach e\` (an bonn logarithm nádúrtha) arna ardú go cumhacht réimse uimhriúil nó léirithe uimhriúil.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Exp
>>> Vector.objects.create(x=5.4, y=-2.0)
>>> vector = Vector.objects.annotate(x_exp=Exp("x"), y_exp=Exp("y")).get()
>>> vector.x_exp, vector.y_exp
(221.40641620418717, 0.1353352832366127)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Exp
>>> FloatField.register_lookup(Exp)
>>> # Get vectors whose exp() is greater than 10
>>> vectors = Vector.objects.filter(x__exp__gt=10, y__exp__gt=10)
```

### `Urlár`

#### `class Floor(expression, **extra)`

Tugann sé an luach sláireach is mó nach mó ná réimse uimhriúil nó léiriú uimhriúil.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Floor
>>> Vector.objects.create(x=5.4, y=-2.3)
>>> vector = Vector.objects.annotate(x_floor=Floor("x"), y_floor=Floor("y")).get()
>>> vector.x_floor, vector.y_floor
(5.0, -3.0)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Floor
>>> FloatField.register_lookup(Floor)
>>> # Get vectors whose floor() is greater than 10
>>> vectors = Vector.objects.filter(x__floor__gt=10, y__floor__gt=10)
```

### `Ln`

#### `class Ln(expression, **extra)`

Tugann an logarithm nádúrtha réimse uimhriúil nó léiriú ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Ln
>>> Vector.objects.create(x=5.4, y=233.0)
>>> vector = Vector.objects.annotate(x_ln=Ln("x"), y_ln=Ln("y")).get()
>>> vector.x_ln, vector.y_ln
(1.6863989535702288, 5.4510384535657)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Ln
>>> FloatField.register_lookup(Ln)
>>> # Get vectors whose value greater than e
>>> vectors = Vector.objects.filter(x__ln__gt=1, y__ln__gt=1)
```

### `Log`

#### `class Log(expression1, expression2, **extra)`

Glacann sé le dhá réimse nó abairt uimhriúla agus cuireann sé logarithm an dara ceann ar ais go bonn an chéad cheann.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Log
>>> Vector.objects.create(x=2.0, y=4.0)
>>> vector = Vector.objects.annotate(log=Log("x", "y")).get()
>>> vector.log
2.0
```

### `Mod`

#### `class Mod(expression1, expression2, **extra)`

Glacann sé le dhá réimse nó abairt uimhriúla agus filleann sé an chuid eile den chéad cheann roinnte leis an dara (oibríocht modulo).

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Mod
>>> Vector.objects.create(x=5.4, y=2.3)
>>> vector = Vector.objects.annotate(mod=Mod("x", "y")).get()
>>> vector.mod
0.8
```

### `Pi`

#### `class Pi(**extra)`

Tugann luach an tairiseach matamaiticiúil `π` ar ais.

### Cumhacht \`\`

#### `class Power(expression1, expression2, **extra)`

Glacann sé le dhá réimse nó abairt uimhriúla agus filleann sé luach an chéad cheann a ardaíodh go cumhacht an dara ceann.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Power
>>> Vector.objects.create(x=2, y=-2)
>>> vector = Vector.objects.annotate(power=Power("x", "y")).get()
>>> vector.power
0.25
```

### `Radians`

#### `class Radians(expression, **extra)`

Athraíonn sé réimse nó léiriú uimhriúil ó chéimeanna go radáin.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Radians
>>> Vector.objects.create(x=-90, y=180)
>>> vector = Vector.objects.annotate(x_r=Radians("x"), y_r=Radians("y")).get()
>>> vector.x_r, vector.y_r
(-1.5707963267948966, 3.141592653589793)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Radians
>>> FloatField.register_lookup(Radians)
>>> # Get vectors whose radians are less than 1
>>> vectors = Vector.objects.filter(x__radians__lt=1, y__radians__lt=1)
```

### `Randam`

#### `class Random(**extra)`

Tugann luach randamach ar ais sa raon `0.0 ≤ x <1.0`.

### `Babhna`

#### `class Round(expression, precision=0, **extra)`

Cuireann réimse uimhriúil nó abairt uimhriúil chuig áiteanna deachúla cruinneas (ní mór gur sláimhir a bheith). De réir réamhshocraithe, cruinneann sé go dtí an sláimhir is gaire. Braitheann cibé an bhfuil leathluachanna cruinnithe suas nó síos ar an mbunachar sonraí.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Round
>>> Vector.objects.create(x=5.4, y=-2.37)
>>> vector = Vector.objects.annotate(x_r=Round("x"), y_r=Round("y", precision=1)).get()
>>> vector.x_r, vector.y_r
(5.0, -2.4)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Round
>>> FloatField.register_lookup(Round)
>>> # Get vectors whose round() is less than 20
>>> vectors = Vector.objects.filter(x__round__lt=20, y__round__lt=20)
```

### `Comhartha`

#### `class Sign(expression, **extra)`

Tugann sé an comhartha (-1, 0, 1) de réimse uimhriúil nó léiriú ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Sign
>>> Vector.objects.create(x=5.4, y=-2.3)
>>> vector = Vector.objects.annotate(x_sign=Sign("x"), y_sign=Sign("y")).get()
>>> vector.x_sign, vector.y_sign
(1, -1)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Sign
>>> FloatField.register_lookup(Sign)
>>> # Get vectors whose signs of components are less than 0.
>>> vectors = Vector.objects.filter(x__sign__lt=0, y__sign__lt=0)
```

### `Sin`

#### `class Sin(expression, **extra)`

Tugann sé sin réimse nó léirithe uimhriúil ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Sin
>>> Vector.objects.create(x=5.4, y=-2.3)
>>> vector = Vector.objects.annotate(x_sin=Sin("x"), y_sin=Sin("y")).get()
>>> vector.x_sin, vector.y_sin
(-0.7727644875559871, -0.7457052121767203)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Sin
>>> FloatField.register_lookup(Sin)
>>> # Get vectors whose sin() is less than 0
>>> vectors = Vector.objects.filter(x__sin__lt=0, y__sin__lt=0)
```

### `Cearr`

#### `class Sqrt(expression, **extra)`

Tugann sé fréamh cearnach réimse nó léirithe uimhriúil neamhdhiúltach ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Sqrt
>>> Vector.objects.create(x=4.0, y=12.0)
>>> vector = Vector.objects.annotate(x_sqrt=Sqrt("x"), y_sqrt=Sqrt("y")).get()
>>> vector.x_sqrt, vector.y_sqrt
(2.0, 3.46410)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Sqrt
>>> FloatField.register_lookup(Sqrt)
>>> # Get vectors whose sqrt() is less than 5
>>> vectors = Vector.objects.filter(x__sqrt__lt=5, y__sqrt__lt=5)
```

### `Tan`

#### `class Tan(expression, **extra)`

Tugann sé tagent réimse nó léirithe uimhriúil ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Tan
>>> Vector.objects.create(x=0, y=12)
>>> vector = Vector.objects.annotate(x_tan=Tan("x"), y_tan=Tan("y")).get()
>>> vector.x_tan, vector.y_tan
(0.0, -0.6358599286615808)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Tan
>>> FloatField.register_lookup(Tan)
>>> # Get vectors whose tangent is less than 0
>>> vectors = Vector.objects.filter(x__tan__lt=0, y__tan__lt=0)
```

## Feidhmeanna téacs

### `Chr`

#### `class Chr(expression, **extra)`

Glacann sé le réimse nó léiriú uimhriúil agus cuireann sé léiriú téacs an abairt ar ais mar charachtar amháin. Oibríonn sé mar an gcéanna le feidhm Python: Func: chr.

Cosúil le: Class: Fad \`, is féidir é a chlárú mar chlaochlú ar \`\`Integerfield. Is é `chr` an t-ainm cuardaigh réamhshocraithe.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Chr
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.filter(name__startswith=Chr(ord("M"))).get()
>>> print(author.name)
Margaret Smith
```

### `Concat`

#### `class Concat(*expressions, **extra)`

Glacann sé le liosta de dhá réimse nó abairt téacs ar a laghad agus cuireann sé an téacs comhtháite ar ais. Caithfidh gach argóint a bheith de chineál téacs nó char. Más mian leat ```textField () ``a chomhcheangal le ``charField ()```, ansin bí cinnte a rá le Django gur chóir go mbeadh an `output_field` ina textField () \`. Teastaíonn `output_field` a shonrú freisin agus `Luach` á gcomhcheangal mar atá sa sampla thíos.

Ní bheidh toradh neall ag an bhfeidhm seo riamh. Ar chúltaca ina bhfuil an abairt iomlán neall mar thoradh ar argóint neall, cinnteoidh Django go ndéantar gach cuid null a thiontú go sreang folamh ar dtús.

Sampla úsáide:

```pycon
>>> # Get the display name as "name (goes_by)"
>>> from django.db.models import CharField, Value as V
>>> from django.db.models.functions import Concat
>>> Author.objects.create(name="Margaret Smith", goes_by="Maggie")
>>> author = Author.objects.annotate(
...     screen_name=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField())
... ).get()
>>> print(author.screen_name)
Margaret Smith (Maggie)
```

### Ar Chlé \`

#### `class Left(expression, length, **extra)`

Tugann sé na chéad charachtair fad den réimse téacs nó an léiriú téacs a thugtar ar ais.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Left
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(first_initial=Left("name", 1)).get()
>>> print(author.first_initial)
M
```

### Fad \`\`

#### `class Length(expression, **extra)`

Glacann sé le réimse téacs amháin nó léiriú agus filleann sé líon na gcarachtar atá ag an luach. Má tá an abairt neall, ansin beidh an fad niall freisin.

Sampla úsáide:

```pycon
>>> # Get the length of the name and goes_by fields
>>> from django.db.models.functions import Length
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(
...     name_length=Length("name"), goes_by_length=Length("goes_by")
... ).get()
>>> print(author.name_length, author.goes_by_length)
(14, None)
```

Is féidir é a chlárú freisin mar chlaochlú. Mar shampla:

```pycon
>>> from django.db.models import CharField
>>> from django.db.models.functions import Length
>>> CharField.register_lookup(Length)
>>> # Get authors whose name is longer than 7 characters
>>> authors = Author.objects.filter(name__length__gt=7)
```

### `` `Íoslag ``

#### `class Lower(expression, **extra)`

Glacann sé le réimse nó léiriú téacs amháin agus filleann sé an léiriú beaga ar ais.

Is féidir é a chlárú freisin mar chlaochlú mar a thuairiscítear in:class: Fad.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Lower
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(name_lower=Lower("name")).get()
>>> print(author.name_lower)
margaret smith
```

### `Lpad`

#### `class LPad(expression, length, fill_text=Value(' '), **extra)`

Filleann luach an réimse téacs nó an léirithe téacs a thugtar a chuirtear ar an taobh clé le fill\_text\` ionas gurb é carachtair ```fad ``an luach mar thoradh air sin. Is é an réamhshocraithe ``fill_text``` spás.

Sampla úsáide:

```pycon
>>> from django.db.models import Value
>>> from django.db.models.functions import LPad
>>> Author.objects.create(name="John", alias="j")
>>> Author.objects.update(name=LPad("name", 8, Value("abc")))
1
>>> print(Author.objects.get(alias="j").name)
abcaJohn
```

### Ltrim \`\`

#### `class LTrim(expression, **extra)`

Cosúil le:class: ~Django.db.Models.Functions.Trim, ach ní bhaineann sé ach spásanna tosaigh.

### `MD5`

#### `class MD5(expression, **extra)`

Glacann sé le réimse téacs amháin nó léiriú agus filleann sé hash MD5 an teaghrán ar ais.

Is féidir é a chlárú freisin mar chlaochlú mar a thuairiscítear in:class: Fad.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import MD5
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(name_md5=MD5("name")).get()
>>> print(author.name_md5)
749fb689816b2db85f5b169c2055b247
```

### `Ord`

#### `class Ord(expression, **extra)`

Glacann sé le réimse téacs amháin nó léiriú agus filleann sé luach pointe cód Unicode ar ais don chéad charachtar den abairt sin. Oibríonn sé cosúil le feidhm Python: Func: ord, ach ní ardaítear eisceacht má tá an abairt níos mó ná carachtar amháin ar fad.

Is féidir é a chlárú freisin mar chlaochlú mar a thuairiscítear in:class: Fad. Is é ord\` an t-ainm cuardaigh réamhshocraithe.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Ord
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(name_code_point=Ord("name")).get()
>>> print(author.name_code_point)
77
```

### Athsheol\`

#### `class Repeat(expression, number, **extra)`

Tugann sé luach an réimse téacs nó na léirithe téacs a thugtar arís agus arís eile uimhir uimhir.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Repeat
>>> Author.objects.create(name="John", alias="j")
>>> Author.objects.update(name=Repeat("name", 3))
1
>>> print(Author.objects.get(alias="j").name)
JohnJohnJohn
```

### `Athraithe`

#### `class Replace(expression, text, replacement=Value(''), **extra)`

Cuirtear `athsholáthair` in `léirithe` in léirithe\` in léirithe\` in ionad téacs . Is é an téacs athsholáthair réamhshocraithe an teaghrán folamh. Tá na hargóintí leis an bhfeidhm íogair ó chásanna.

Sampla úsáide:

```pycon
>>> from django.db.models import Value
>>> from django.db.models.functions import Replace
>>> Author.objects.create(name="Margaret Johnson")
>>> Author.objects.create(name="Margaret Smith")
>>> Author.objects.update(name=Replace("name", Value("Margaret"), Value("Margareth")))
2
>>> Author.objects.values("name")
<QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>
```

### `` `Ag siom ``

#### `class Reverse(expression, **extra)`

Glacann sé le réimse téacs amháin nó léiriú agus cuireann sé carachtair na léirithe sin ar ais in ord droim.

Is féidir é a chlárú freisin mar chlaochlú mar a thuairiscítear in:class: Fad. Is é `reverse` an t-ainm cuardaigh réamhshocraithe.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Reverse
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(backward=Reverse("name")).get()
>>> print(author.backward)
htimS teragraM
```

### Ceart \`

#### `class Right(expression, length, **extra)`

Tugann sé ar ais na carachtair deireanacha fad den réimse téacs nó an léiriú téacs a thugtar.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Right
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(last_letter=Right("name", 1)).get()
>>> print(author.last_letter)
h
```

### `Rpad`

#### `class RPad(expression, length, fill_text=Value(' '), **extra)`

Cosúil le:class: ~django.db.models.functions.lpad, ach ceapáin ar an taobh dheis.

### Rtrim \`\`

#### `class RTrim(expression, **extra)`

Cosúil le:class: ~Django.db.Models.Functions.Trim, ach ní bhaineann sé ach spásanna imeachta.

### `SHA1`, SHA224\`, SHA256\`, SHA384\`, agus `SHA512`

#### `class SHA1(expression, **extra)`

#### `class SHA224(expression, **extra)`

#### `class SHA256(expression, **extra)`

#### `class SHA384(expression, **extra)`

#### `class SHA512(expression, **extra)`

Glacann sé le réimse téacs amháin nó léiriú agus filleann sé hash áirithe an teaghrán ar ais.

Is féidir iad a chlárú freisin mar athruithe mar a thuairiscítear in:class: Fad.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import SHA1
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(name_sha1=SHA1("name")).get()
>>> print(author.name_sha1)
b87efd8a6c991c390be5a68e8a7945a7851c7e5c
```

> **PostgreSQL**
>
> \< <https://www.postgresql.org/docs/current/> pgcrypto.html\>Caithfear an  a shuiteáil. Is féidir leat an oibríocht imirce:class: ~django.contrib.postgres.operations.cryptoextension a úsáid chun é a shuiteáil.

> **Oracle**
>
> Ní thacaíonn Oracle leis an bhfeidhm `SHA224`.

### `StrIndex`

#### `class StrIndex(expression, substring, **extra)`

Returns a positive integer corresponding to the 1-indexed position of the first
occurrence of `substring` inside `expression`, or 0 if `substring` is not
found.

Sampla úsáide:

```pycon
>>> from django.db.models import Value as V
>>> from django.db.models.functions import StrIndex
>>> Author.objects.create(name="Margaret Smith")
>>> Author.objects.create(name="Smith, Margaret")
>>> Author.objects.create(name="Margaret Jackson")
>>> Author.objects.filter(name="Margaret Jackson").annotate(
...     smith_index=StrIndex("name", V("Smith"))
... ).get().smith_index
0
>>> authors = Author.objects.annotate(smith_index=StrIndex("name", V("Smith"))).filter(
...     smith_index__gt=0
... )
<QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
```

> **Warning**
>
> I MySQL, cinneann tábla bunachar sonraí 's:ref: collation \<mysql-collation\>\`an bhfuil comparáidí teaghráin (mar shampla \`\`léirithe\` agus `foshraithe` den fheidhm seo) cás-íogair. Tá comparáidí neamh-íogair de réir réamhshocraithe.

### `Foshraithe`

#### `class Substr(expression, pos, length=None, **extra)`

Tugann sé fotheagán de fhad ```fad ``ón réimse nó an abairt a thosaíonn ag an suíomh ``pos```. Tá an suíomh 1-innéacsaithe, mar sin caithfidh an seasamh a bheith níos mó ná 0. Más é ```` `fad ```None ````, ansin cuirfear an chuid eile den teaghrán ar ais.

Sampla úsáide:

```pycon
>>> # Set the alias to the first 5 characters of the name as lowercase
>>> from django.db.models.functions import Lower, Substr
>>> Author.objects.create(name="Margaret Smith")
>>> Author.objects.update(alias=Lower(Substr("name", 1, 5)))
1
>>> print(Author.objects.get(name="Margaret Smith").alias)
marga
```

### `Trim`

#### `class Trim(expression, **extra)`

Tugann sé luach an réimse nó an léirithe téacs a thugtar ar ais le spásanna tosaigh agus leantacha bainte.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Trim
>>> Author.objects.create(name="  John  ", alias="j")
>>> Author.objects.update(name=Trim("name"))
1
>>> print(Author.objects.get(alias="j").name)
John
```

### `Uachtar`

#### `class Upper(expression, **extra)`

Glacann sé le réimse nó léiriú téacs amháin agus cuireann sé an léiriú uachtarchlóir ar ais

Is féidir é a chlárú freisin mar chlaochlú mar a thuairiscítear in:class: Fad.

Sampla úsáide:

```pycon
>>> from django.db.models.functions import Upper
>>> Author.objects.create(name="Margaret Smith")
>>> author = Author.objects.annotate(name_upper=Upper("name")).get()
>>> print(author.name_upper)
MARGARET SMITH
```

## Feidhmeanna fuinn

Tá roinnt feidhmeanna le húsáid in a:class: ~Django.db.Models.Expressions.Window léiriú chun céim na n-eilimintí nó an: aicme: Ntile de roinnt sraitheanna a ríomh.

### `Cumedist`

#### `class CumeDist(*expressions, **extra)`

Ríomhann dáileadh carnach luach laistigh de fhuinneog nó deighilt. Sainmhínítear an dáileadh carnach mar líon na sraitheanna roimh an tsraith reatha nó a chuirtear leis an tsraith reatha roinnte le líon iomlán na sraitheanna sa fhráma.

### `Denserank`

#### `class DenseRank(*expressions, **extra)`

Coibhéiseach len:class: Rank ach níl bearnaí aige.

### `Chéadluach`

#### `class FirstValue(expression, **extra)`

Filleann sé an luach a mheastófar ag an tsraith arb é an chéad shraith den fhráma fuinneoige, nó Níl mura bhfuil aon luach den sórt sin ann.

### `Lag`

#### `class Lag(expression, offset=1, default=None, **extra)`

Ríomhann an luach a fhritháireamh le `offset`, agus mura bhfuil aon tsraith ann, filleann sé `default`.

Caithfidh `réamhshocraithe` an cineál céanna a bheith ag an léiritheo\`, áfach, ní bhailítear é seo ach ag an mbunachar sonraí agus ní i Python.

> **MariaDB agus default**
>
> \< <https://jira.mariadb.org/browse/MDEV-12981>\>MariaDB ní thacaíonn \`\_ leis an bparaiméadar \`\`réamhshocraithe\`.

### Luach deiridh \`\`

#### `class LastValue(expression, **extra)`

Inchomparáide len:class: FirstValue, ríomhann sé an luach deireanach i gclásal fráma ar leith.

### `Luaide`

#### `class Lead(expression, offset=1, default=None, **extra)`

\<window-frames\>Ríomhann an luach tosaigh i dtugtar: ref: fráma \`. Déantar meastóireacht ar \`\`offset\` agus `default` araon maidir leis an tsraith reatha.

Caithfidh `réamhshocraithe` an cineál céanna a bheith ag an léiritheo\`, áfach, ní bhailítear é seo ach ag an mbunachar sonraí agus ní i Python.

> **MariaDB agus default**
>
> \< <https://jira.mariadb.org/browse/MDEV-12981>\>MariaDB ní thacaíonn \`\_ leis an bparaiméadar \`\`réamhshocraithe\`.

### `Nthluach`

#### `class NthValue(expression, nth=1, **extra)`

Ríomhann an tsraith i gcoibhneas leis an bhfritháireamh `nth` (caithfidh a bheith ina luach dearfach) laistigh den fhuinneog. Tugann sé ar ais `None` mura bhfuil aon tsraith ann.

Féadfaidh roinnt bunachair sonraí n-luach nach bhfuil ann a láimhseáil go difriúil. Mar shampla, filleann Oracle sreang folamh seachas None le haghaidh nathanna carachtarbhunaithe. Ní dhéanann Django aon tiontaithe sna cásanna seo.

### Ntile \`\`

#### `class Ntile(num_buckets=1, **extra)`

Ríomhann deighilt do gach ceann de na sraitheanna sa chlásal fráma, ag dáileadh uimhreacha chomh cothrom agus is féidir idir 1 agus `num_buckets`. Mura roinntear na sraitheanna go cothrom i roinnt buicéad, cuirfear buicéad amháin nó níos mó ionadaíocht níos minice.

### `Rang céatadáin`

#### `class PercentRank(*expressions, **extra)`

Ríomhann céim choibhneasta na sraitheanna sa chlásal fráma. Tá an ríomh seo comhionann le measúnú a dhéanamh ar:

```text
(rank - 1) / (total rows - 1)
```

Míníonn an tábla seo a leanas an ríomh maidir le céim choibhneasta a chéile:

| Sraith # | Luach | Céim | ríomh | Rang Choibhneasta |
| --- | --- | --- | --- | --- |
| 1 | 15 | 1 | (1-1)/(7-1) | 0.0000 |
| 2 | 20 | 2 | (2-1)/(7-1) | 0.1666 |
| 3 | 20 | 2 | (2-1)/(7-1) | 0.1666 |
| 4 | 20 | 2 | (2-1)/(7-1) | 0.1666 |
| 5 | 30 | 5 | (5-1)/(7-1) | 0.6666 |
| 6 | 30 | 5 | (5-1)/(7-1) | 0.6666 |
| 7 | 40 | 7 | (7-1)/(7-1) | 1.0000 |

### `Rang`

#### `class Rank(*expressions, **extra)`

Inchomparáide len:class: RowNumber, rangaíonn an fheidhm seo sraitheanna san fhuinneog. Tá bearnaí sa chéim ríomhaithe. Úsáid: aicme: Denserank chun céim a ríomh gan bearnaí.

### `Uimhir Sraigh`

#### `class RowNumber(*expressions, **extra)`

\<window-frames\>Ríomhann sé uimhir an tsraith de réir ordú an chlásal fráma nó ordú na fiosrúcháin iomláine mura ndéantar deighilt an:ref: fráma fuinneoige .
