---
title: "Optamú ar rochtain bunachar"
version: 6.1
locale: ga
source: https://docs.djangoproject.com/ga/6.1/topics/db/optimization/
canonical: https://djangodocs.dev/ga/6.1/topics/db/optimization/
---
# Optamú ar rochtain bunachar

Soláthraíonn ciseal bunachar sonraí Django bealaí éagsúla chun cabhrú le forbróirí an leas is fearr a bhaint as a mbunachar Bailíonn an doiciméad seo naisc leis an doiciméad ábhartha le chéile, agus cuireann sé leideanna éagsúla leis, eagraithe faoi roinnt ceannteidil a thugann cur síos ar na céimeanna atá le glacadh agus tú ag iarraidh úsáid do bhunachar sonraí a

## Próifíl ar dtús

Mar chleachtas cláraithe ginearálta, téann sé seo gan rá. \<faq-see-raw-sql-queries\>Faigh amach: ref: cad iad na ceisteanna atá á dhéanamh agat agus cad a chosnaíonn siad duit \`. Úsáid: Meth: \`.querySet.explain chun tuiscint a fháil ar cé chomh sonrach a fhorghníomhaíonn do bhunachar sonraí `QuerySet`s. B'fhéidir gur mhaith leat tionscadal seachtrach a úsáid freisin cosúil:pypi: django-debug-toolbar, nó uirlis a dhéanann monatóireacht díreach ar do bhunachar sonraí.

Cuimhnigh go bhféadfadh tú a bheith ag barrfheabhsú le haghaidh luas nó cuimhne nó araon, ag brath ar do riachtanais Uaireanta beidh barrfheabhsú do cheann amháin díobhálach don cheann eile, ach uaireanta cabhróidh siad lena chéile. Chomh maith leis sin, b'fhéidir nach mbeadh an costas céanna (duitse) ag an obair a dhéanann an próiseas bunachar sonraí leis an méid céanna oibre a dhéantar i do phróiseas Python. Is fútsa atá sé cinneadh a dhéanamh cad iad do thosaíochtaí, cá gcaithfidh an t-iarmhéid a bheith, agus iad seo go léir a phróifíliú de réir mar is gá ós rud é go mbeidh sé seo ag brath ar d'iarratas agus ar d'fhre

Le gach rud a leanann, cuimhnigh próifíl a dhéanamh tar éis gach athraithe chun a chinntiú gur sochar é an t-athrú, agus sochar mór go leor i bhfianaise an laghdú ar inléiteacht do chód. \*\* Tagann gach ceann de na moltaí thíos leis an rabhadh go bhféadfadh an prionsabal ginearálta a bheith i bhfeidhm i do chúinsí, nó go bhféadfadh sé a aisiompú fiú.

## Bain úsáid as teicnící caighdeánacha

... lena n-áirítear:

- [Indexes](https://en.wikipedia.org/wiki/Database_index). This is a number one priority, *after* you have determined from
  profiling what indexes should be added. Use
  [`Meta.indexes`](/ga/6.1/ref/models/options/#django.db.models.Options.indexes) or
  [`Field.db_index`](/ga/6.1/ref/models/fields/#django.db.models.Field.db_index) to add these from
  Django. Consider adding indexes to fields that you frequently query using
  [`filter()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.filter),
  [`exclude()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.exclude),
  [`order_by()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.order_by), etc. as indexes may help
  to speed up lookups. Note that determining the best indexes is a complex
  database-dependent topic that will depend on your particular application.
  The overhead of maintaining an index may outweigh any gains in query speed.

- Úsáid chuí de chineálacha réimse.

Glacfaimid leis go ndearna tú na rudaí atá liostaithe thuas. Díríonn an chuid eile den doiciméad seo ar conas Django a úsáid sa chaoi nach bhfuil tú ag déanamh obair gan ghá. Ní thugann an doiciméad seo aghaidh freisin ar theicnící optamaithe eile a bhaineann le gach oibríocht daor, mar shampla:doc: taiscáil cuspóir ginear\</topics/cache\> álta.

## Tuiscint a fháil ar `QuerySet`s

Tuiscint: doc: Tá QuerySets \</ref/models/querysets\> ríthábhachtach chun feidhmíocht mhaith a fháil le cód simplí. Go háirithe:

### Meastóireacht QuerySet a thuiscint

Chun fadhbanna feidhmíochta a sheachaint, tá sé tábhachtach tuiscint:

- \<querysets-are-lazy\>that:ref: Tá ceisteanna leisciúil .
- \<when-querysets-are-evaluated\>when: ref: déantar iad a mheas .
- \<caching-and-querysets\>cona:ref: coinnítear na sonraí i gcuimhne .

### Tréithe taiscéadta a thuiscint

Chomh maith le caistriú an QuerySet iomlán, tá toradh tréithe ar rudaí ORM a chaitheamh a chaitheamh. Go ginearálta, déanfar tréithe nach féidir glaoch a stóráil. \<queryset-model-example\>Mar shampla, ag glacadh leis na:ref: samplaí blag samplacha :

```pycon
>>> entry = Entry.objects.get(id=1)
>>> entry.blog  # Blog object is retrieved at this point
>>> entry.blog  # cached version, no DB access
```

Ach go ginearálta, is cúis le tréithe inghlaonta cuardach DB gach uair:

```pycon
>>> entry = Entry.objects.get(id=1)
>>> entry.authors.all()  # query performed
>>> entry.authors.all()  # query performed again
```

Bí cúramach agus tú ag léamh cód teimpléid - ní cheadaíonn an córas teimpléid lúibíní a úsáid, ach glaoifidh sé glaonna go huathoibríoch, ag folach an t-idirdhealú thuas.

Bí cúramach le d'airíonna saincheaptha féin - is fútsa atá sé caching a chur i bhfeidhm nuair is gá, mar shampla ag baint úsáide as an maisitheoir: class: ~django.utils.functional.cached\_property.

### Úsáid an chlib teimpléad with\`

Chun úsáid a bhaint as iompar caching QuerySet , b'fhéidir go mbeidh ort an chlib teimpléad:ttag: with a úsáid.

### Úsáid iterator () \`\`

When you have a lot of objects, the caching behavior of the `QuerySet` can
cause a large amount of memory to be used. In this case,
[`iterator()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.iterator) may help.

### Úsáid mhínigh () \`\`

[`QuerySet.explain()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.explain) gives you detailed information about how the database
executes a query, including indexes and joins that are used. These details may
help you find queries that could be rewritten more efficiently, or identify
indexes that could be added to improve performance.

## An oibríonn bunachar sonraí sa bhunachar sonraí seachas i Python

Mar shampla:

- Ag an leibhéal is bunúsaí, bain úsáid as: ref: scagadh agus eisiamh \<queryset-api\>\`chun scagadh a dhéanamh sa bhunachar sonraí.
- Use [Nathanna \`\`F () \`\`](/ga/6.1/ref/models/expressions/#f-expressions) to filter based on other fields within the same
  model.
- Úsáid:doc: anótáil chun comhiomlánú a dhéanamh sa bhunachar sonraithe' \</topics/db/aggregation\>.

Mura leor iad seo chun an SQL a theastaíonn uait a ghiniúint:

### Úsáid `Rawsql`

Modh nach bhfuil chomh iniompartha ach níos cumhachtaí ná an léir:class: ~Django.db.Models.Expressions.RawSql, a ligeann roinnt SQL a chur go sainráite leis an bhfiosrúchán. Mura bhfuil sé sin cumhachtach go leor fós:

### Úsáid SQL amh

Scríobh do chuid féin: doc: SQL saincheaptha chun sonraí a aisghabháil nó samhlacha a dhaonrú '\</topics/db/sql\>. Úsáid \`\`django.db.connection.queries\` chun a fháil amach cad atá ag scríobh Django duit agus tosú as sin.

## Aisghabháil rudaí aonair ag úsáid colún uathúil, innéacsaithe

Tá dhá chúis ann le colún a úsáid le:attr: ~django.db.models.field.unique nó:attr: ~django.db.models.field.db\_index agus tú ag úsáid: meth: ~django.db.models.queryset.get chun rudaí aonair a aisghabháil. Ar dtús, beidh an cheist níos gasta mar gheall ar an innéacs bunachar sonraí bunúsach. Chomh maith leis sin, d'fhéadfadh an cheist rith i bhfad níos moille má mheaitseálann ilrudaí leis an lorg; ráthaíonn srian uathúil a bheith agat ar an gcolún nach dtarlóidh sé seo riamh.

\<queryset-model-example\>Mar sin ag baint úsáide as an: ref: sampla samhlacha blag :

```pycon
>>> entry = Entry.objects.get(id=10)
```

beidh sé níos gasta ná:

```pycon
>>> entry = Entry.objects.get(headline="News Item Title")
```

toisc go ndéanann an bunachar sonraí innéacsaithe id agus ráthaítear go mbeidh sé uathúil.

D'fhéadfadh sé go mbeadh sé mall go leor na nithe seo a leanas

```pycon
>>> entry = Entry.objects.get(headline__startswith="News")
```

Ar an gcéad dul síos, ní innéacsaítear ceannlíne , rud a fhágfaidh go bhfaighidh an bunachar sonraí bunúsach níos moille.

Second, the lookup may return multiple results. Even though Django applies a
limit of 21 objects when using [`get()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.get),
the database may still need to scan everything to evaluate a non-unique
condition. Narrowing your query up-front is more efficient.

## Retrieve related objects efficiently

Generally, accessing the database multiple times to retrieve different parts
of a single "set" of data is less efficient than retrieving it all in one
query. This is particularly important if you have a query that is executed in a
loop, and could therefore end up doing many database queries, when only one
is needed. Below are some techniques to combine queries for efficiency.

### Use the `FETCH_PEERS` fetch mode

Use the [`FETCH_PEERS`](/ga/6.1/topics/db/fetch-modes/#django.db.models.FETCH_PEERS) fetch mode to make on-demand
field access more efficient with bulk-fetching. Enable it for all usage of
your models [with a custom manager](/ga/6.1/topics/db/fetch-modes/#fetch-modes-custom-manager).

Using this fetch mode is easier than declaring fields to fetch with
[`select_related()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related) or
[`prefetch_related()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related), especially when it's
hard to predict which fields will be accessed.

### Úsáid ```QuerySet.Select_related () ``agus ``prefetch_related ()```

When the [`FETCH_PEERS`](/ga/6.1/topics/db/fetch-modes/#django.db.models.FETCH_PEERS) fetch mode is not appropriate or
efficient enough, use [`select_related()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related)
and [`prefetch_related()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related). Understand their
documentation thoroughly and apply them where needed.

It may be useful to apply these methods in [managers and default managers](/ga/6.1/topics/db/managers/). Be aware when your manager is and is not used; for
example, related object access [uses the base manager](/ga/6.1/topics/db/managers/#managers-for-related-objects) rather than the default manager.

### Use `prefetch_related_objects()`

Where [`prefetch_related`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related) would be useful
after the queryset has been evaluated, use
[`prefetch_related_objects()`](/ga/6.1/ref/models/querysets/#django.db.models.prefetch_related_objects) to execute an extra
prefetch.

## Ná aisghabháil rudaí nach dteastaíonn uait

### Úsáid ```QuerySet.values () ``agus ``values_list ()```

When you only want a `dict` or `list` of values, and don't need ORM model
objects, make appropriate usage of
[`values()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.values).
These can be useful for replacing model objects in template code - as long as
the dicts you supply have the same attributes as those used in the template,
you are fine.

### Úsáid ```QuerySet.defer () ``agus ``only ()```

Use [`defer()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.defer) and
[`only()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.only) if there are database columns
you know that you won't need (or won't need in most cases) to avoid loading
them. Note that if you *do* use them, the ORM will have to go and get them in
a separate query, making this a pessimization if you use it inappropriately.

Ná bí ró-ionsaitheach agus réimsí a chur ar iarchur gan próifíliú mar caithfidh an bunachar sonraí an chuid is mó de na sonraí neamh-téacs, neamh-Varchar a léamh ón diosca ar feadh sraith amháin sna torthaí, fiú mura gcríochnaíonn sé ach cúpla colún á úsáid. Tá na modhanna ```defer () ``agus ``only ()``` is úsáideach nuair is féidir leat a lán sonraí téacs a luchtú a sheachaint nó do réimsí a d'fhéadfadh go leor próiseála a thógáil chun tiontú ar ais go Python. Mar is gnách, próifíl ar dtús, ansin barrfheabhsú.

### Úsáid QuerySet.contents (obj) \`\`

... mura dteastaíonn uait ach a fháil amach an bhfuil ```obj ``sa tacar fiosrúcháin, seachas ``if obj in iarratas```.

### Úsáid QuerySet.count () \`\`

... mura dteastaíonn uait ach an comhaireamh, seachas len (queryset) a dhéanamh.

### Úsáid QuerySet.exists () \`\`

... mura dteastaíonn uait ach a fháil amach an bhfuil toradh amháin ar a laghad ann, seachas if queryset .

Ach:

### Ná ró-úsáid ```tá () ``, `count ()```, agus `ann ()`

Má tá sonraí eile ag teastáil uait ón QuerySet, déan iad a mheas láithreach.

Mar shampla, ag glacadh le samhail `Grúpa` a bhfuil gaol go leor aige le Úsáideoir , is fearr an cód seo a leanas:

```
members = group.members.all()

if display_group_members:
    if members:
        if current_user in members:
            print("You and", len(members) - 1, "other users are members of this group.")
        else:
            print("There are", len(members), "members in this group.")

        for member in members:
            print(member.username)
    else:
        print("There are no members in this group.")
```

Tá sé is fearr mar gheall ar:

1. Ós rud é go bhfuil QuerySets leisciúil, ní dhéanann sé seo aon cheisteanna bunachar sonraí má tá `display_group_members` False\`.
2. Trí stóráil ```group.members.all () ``sa athróg ``members``` is féidir a taisce torthaí a athúsáid.
3. Tá an líne ```if comhaltaí: ``is cúis le ``QuerySet. __bool__ () ``le glaoch, rud a fhágann go ndéanfar an ceist ``group.members.all ()``` a reáchtáil ar an mbunachar sonraí. Mura bhfuil aon torthaí ann, cuirfidh sé ar ais `False`, ar shlí eile `True`.
4. Seiceálann an líne if current\_user i gcomhaltaí: an bhfuil an t-úsáideoir sa taisce torthaí, mar sin ní eisítear aon cheisteanna breise bunachar sonraí.
5. Glaonn úsáid len (comhaltaí) QuerySet. \_\_len\_\_ () \`, ag athúsáid taisce na dtorthaí, mar sin arís, ní eisítear aon cheisteanna bunachar sonraí.
6. Athraíonn an lúb for ball\` thar taisce na torthaí.

San iomlán, déanann an cód seo ceisteanna bunachar sonraí amháin nó nialas. Is é an t-aon bharrfheabhsú d'aon ghnó a dhéantar ná an athróg ```baill ``a úsáid. Ag baint úsáide as ``QuerySet.exists () ``don `if```, QuerySet.contents () \`\`\`, `` `in ``, nó QuerySet.count () don chomhaireamh bheadh ceisteanna breise ina chúis le ceisteanna breise.

### Úsáid ```QuerySet.Update () ``agus ``delete ()```

\<topics-db-queries-update\>Seachas ualach rudaí a aisghabháil, socraigh roinnt luachanna, agus iad a shábháil aonair, bain úsáid as ráiteas mórchóir SQL UPDATE, trí:ref: QuerySet.update () . \<topics-db-queries-delete\>Ar an gcaoi chéanna, déan:ref: bulk scriosann nuair is féidir.

Tabhair faoi deara, áfach, nach féidir leis na modhanna mór-nuashonraithe seo na modhanna ```save () ``nó ``delete ()``` cásanna aonair a ghlaoch, rud a chiallaíonn nach gcuirfear aon iompar saincheaptha a chuir tú leis do na modhanna seo a fhorghníomhú, lena n-áirítear aon rud atá tiomáinte ón ngnáthréad bunachar sonraí: doc: signals \</ref/signals\>.

### Úsáid luachanna eachtracha go díreach

Mura dteastaíonn uait ach luach eochair eachtrach, bain úsáid as an eochairluach eachtrach atá ar an réad atá agat cheana féin, seachas an réad gaolmhar iomlán a fháil agus a phríomh-eochair a ghlacadh. ie déan:

```
entry.blog_id
```

in ionad:

```
entry.blog.id
```

### Ná ordaigh torthaí mura bhfuil cúram ort

Ordering is not free; each field to order by is an operation the database must
perform. If a model has a default ordering ([`Meta.ordering`](/ga/6.1/ref/models/options/#django.db.models.Options.ordering)) and you don't need it, remove
it on a `QuerySet` by calling
[`order_by()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.order_by) with no parameters.

D'fhéadfadh innéacs a chur le do bhunachar sonraí cabhrú le feidhmíocht ordaithe a fheabhsú

## Úsáid modhanna mórchóir

Úsáid modhanna mórchóir chun líon na ráitis SQL a laghdú.

### Cruthaigh ar an mórchóir

When creating objects, where possible, use the
[`bulk_create()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create) method to reduce the
number of SQL queries. For example:

```
Entry.objects.bulk_create(
    [
        Entry(headline="This is a test"),
        Entry(headline="This is only a test"),
    ]
)
```

... is fearr ná:

```
Entry.objects.create(headline="This is a test")
Entry.objects.create(headline="This is only a test")
```

Note that [`bulk_create()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create) has several
caveats, so ensure it's appropriate for your use case.

### Nuashonrú i mórchóir

When updating objects, where possible, use the
[`bulk_update()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.bulk_update) method to reduce the
number of SQL queries. Given a list or queryset of objects:

```
entries = Entry.objects.bulk_create(
    [
        Entry(headline="This is a test"),
        Entry(headline="This is only a test"),
    ]
)
```

An sampla seo a leanas:

```
entries[0].headline = "This is not a test"
entries[1].headline = "This is no longer a test"
Entry.objects.bulk_update(entries, ["headline"])
```

... is fearr ná:

```
entries[0].headline = "This is not a test"
entries[0].save()
entries[1].headline = "This is no longer a test"
entries[1].save()
```

Note that [`bulk_update()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.bulk_update) has several
caveats, so ensure it's appropriate for your use case.

### Cuir isteach sa mórchóir

Agus rudaí á chur isteach ion:class: ManyTomanyFields \<django.db.models.ManyToManyField\>, bain úsáid as: meth: ~Django.db.Models.Fields.Related.RelatedManager.Add le rudaí iolracha chun líon na gceisteanna SQL a laghdú. Mar shampla:

```
my_band.members.add(me, my_friend)
```

... is fearr ná:

```
my_band.members.add(me)
my_band.members.add(my_friend)
```

...where `Band` and `Artist` are models with a many-to-many relationship.

When inserting different pairs of objects into
[`ManyToManyField`](/ga/6.1/ref/models/fields/#django.db.models.ManyToManyField) or when the custom
[`through`](/ga/6.1/ref/models/fields/#django.db.models.ManyToManyField.through) table is defined, use
[`bulk_create()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create) method to reduce the
number of SQL queries. For example:

```
PizzaToppingRelationship = Pizza.toppings.through
PizzaToppingRelationship.objects.bulk_create(
    [
        PizzaToppingRelationship(pizza=my_pizza, topping=pepperoni),
        PizzaToppingRelationship(pizza=your_pizza, topping=pepperoni),
        PizzaToppingRelationship(pizza=your_pizza, topping=mushroom),
    ],
    ignore_conflicts=True,
)
```

... is fearr ná:

```
my_pizza.toppings.add(pepperoni)
your_pizza.toppings.add(pepperoni, mushroom)
```

... áit a bhfuil caidreamh go leor ag Pizza\` agus `Topping`. Tabhair faoi deara go bhfuil roinnt de: meth: rabhadh don mhodh seo \<django.db.models.query.QuerySet.bulk\_create\>, mar sin déan cinnte go bhfuil sé oiriúnach do do chás úsáide.

### Bain ar an mórchóir

Agus rudaí á bhaint as: class: ManyTomanyFields \<django.db.models.ManyToManyField\>, bain úsáid as: meth: ~Django.db.Models.Fields.Related.RelatedManager.Remove le rudaí iolracha chun líon na gceisteanna SQL a laghdú. Mar shampla:

```
my_band.members.remove(me, my_friend)
```

... is fearr ná:

```
my_band.members.remove(me)
my_band.members.remove(my_friend)
```

...where `Band` and `Artist` are models with a many-to-many relationship.

When removing multiple many-to-many relationships involving several instances
of the related models, use the [`delete()`](/ga/6.1/ref/models/querysets/#django.db.models.query.QuerySet.delete)
method on a filtered queryset of the field's
[`through`](/ga/6.1/ref/models/fields/#django.db.models.ManyToManyField.through) model. By combining multiple
conditions with [\`\`Q () \`\`rudaí](/ga/6.1/ref/models/querysets/#q-objects), you can delete several relationships in a
single query. For example:

```
from django.db.models import Q

PizzaToppingRelationship = Pizza.toppings.through
PizzaToppingRelationship.objects.filter(
    Q(pizza=my_pizza, topping=pepperoni)
    | Q(pizza=your_pizza, topping=pepperoni)
    | Q(pizza=your_pizza, topping=mushroom)
).delete()
```

... is fearr ná:

```
my_pizza.toppings.remove(pepperoni)
your_pizza.toppings.remove(pepperoni, mushroom)
```

... áit a bhfuil caidreamh go leor ag Pizza\` agus `Topping`.
