---
title: "Caidrimh go leor le duine"
version: 6.1
locale: ga
source: https://docs.djangoproject.com/ga/6.1/topics/db/examples/many_to_one/
canonical: https://djangodocs.dev/ga/6.1/topics/db/examples/many_to_one/
---
# Caidrimh go leor le duine

Chun caidreamh go leor le duine a shainiú, bain úsáid as: class: ~django.db.Models.ForeignKey.

Sa sampla seo, is féidir le `Tuairiseoir` a bheith bainteach le go leor rudaí `Airteag`, ach ní féidir ach réad ```Tuairiscitheoir amháin a bheith ag ``Airteag```:

```
from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ["headline"]
```

Seo a leanas samplaí d'oibríochtaí is féidir a dhéanamh ag baint úsáide as na háiseanna API Python.

Cruthaigh cúpla Tuairisceoir:

```pycon
>>> r = Reporter(first_name="John", last_name="Smith", email="john@example.com")
>>> r.save()

>>> r2 = Reporter(first_name="Paul", last_name="Jones", email="paul@example.com")
>>> r2.save()
```

Cruthaigh Airteagal:

```pycon
>>> from datetime import date
>>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
>>> a.save()

>>> a.reporter.id
1

>>> a.reporter
<Reporter: John Smith>
```

Tabhair faoi deara go gcaithfidh tú réad a shábháil sula bhféadfar é a shannadh do phríomhchaidreamh eachtrach. Mar shampla, ardaíonn `Airteag` a chruthú le `Tuairiseoir` neamhshábháilte `` `Error lua ``:

```pycon
>>> r3 = Reporter(first_name="John", last_name="Smith", email="john@example.com")
>>> Article.objects.create(
...     headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3
... )
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.
```

Tá rochtain ag rudaí Airteagail ar a gcuid rudaí Tuairisceora

```pycon
>>> r = a.reporter
```

Cruthaigh Airteagal tríd an réad Tuairisceora:

```pycon
>>> new_article = r.article_set.create(
...     headline="John's second story", pub_date=date(2005, 7, 29)
... )
>>> new_article
<Article: John's second story>
>>> new_article.reporter
<Reporter: John Smith>
>>> new_article.reporter.id
1
```

Cruthaigh alt nua:

```pycon
>>> new_article2 = Article.objects.create(
...     headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r
... )
>>> new_article2.reporter
<Reporter: John Smith>
>>> new_article2.reporter.id
1
>>> r.article_set.all()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
```

Cuir an t-alt céanna le tacar alt difriúil - seiceáil go mbogann sé:

```pycon
>>> r2.article_set.add(new_article2)
>>> new_article2.reporter.id
2
>>> new_article2.reporter
<Reporter: Paul Jones>
```

Ardaíonn réad den chineál mícheart a chur leis TypeError:

```pycon
>>> r.article_set.add(r2)
Traceback (most recent call last):
...
TypeError: 'Article' instance expected, got <Reporter: Paul Jones>

>>> r.article_set.all()
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> r2.article_set.all()
<QuerySet [<Article: Paul's story>]>

>>> r.article_set.count()
2

>>> r2.article_set.count()
1
```

Tabhair faoi deara go bhfuil an t-alt bogadh ó Eoin go Pól sa sampla deireanach.

Tacaíonn bainisteoirí gaolmhara le cuardach allamuigh freisin. Leanann an API caidrimh go huathoibríoch chomh fada agus is gá duit. Úsáid béim dúbailte chun caidrimh a scaradh. Oibríonn sé seo an oiread leibhéil domhain agus is mian leat. Níl aon teorainn ann. Mar shampla:

```pycon
>>> r.article_set.filter(headline__startswith="This")
<QuerySet [<Article: This is a test>]>

# Find all Articles for any Reporter whose first name is "John".
>>> Article.objects.filter(reporter__first_name="John")
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
```

Tá meaitseáil cruinn intuigthe anseo:

```pycon
>>> Article.objects.filter(reporter__first_name="John")
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
```

Fiosrú faoi dhó thar an réimse gaolmhar. Aistríonn sé seo go coinníoll AND sa chlásal WHERE:

```pycon
>>> Article.objects.filter(reporter__first_name="John", reporter__last_name="Smith")
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
```

Maidir leis an gcuardach gaolmhar is féidir leat príomhluach a sholáthar nó an réad gaolmhar a rith go sainráite:

```pycon
>>> Article.objects.filter(reporter__pk=1)
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> Article.objects.filter(reporter=1)
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> Article.objects.filter(reporter=r)
<QuerySet [<Article: John's second story>, <Article: This is a test>]>

>>> Article.objects.filter(reporter__in=[1, 2]).distinct()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
>>> Article.objects.filter(reporter__in=[r, r2]).distinct()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
```

Is féidir leat tacar fiosrúcháin a úsáid freisin in ionad liosta liteartha cásanna:

```pycon
>>> Article.objects.filter(
...     reporter__in=Reporter.objects.filter(first_name="John")
... ).distinct()
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
```

Ag fiosrú sa treo eile:

```pycon
>>> Reporter.objects.filter(article__pk=1)
<QuerySet [<Reporter: John Smith>]>
>>> Reporter.objects.filter(article=1)
<QuerySet [<Reporter: John Smith>]>
>>> Reporter.objects.filter(article=a)
<QuerySet [<Reporter: John Smith>]>

>>> Reporter.objects.filter(article__headline__startswith="This")
<QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
>>> Reporter.objects.filter(article__headline__startswith="This").distinct()
<QuerySet [<Reporter: John Smith>]>
```

Oibríonn comhaireamh sa treo eile i gcomhar le difriúil () :

```pycon
>>> Reporter.objects.filter(article__headline__startswith="This").count()
3
>>> Reporter.objects.filter(article__headline__startswith="This").distinct().count()
1
```

Is féidir le ceisteanna dul timpeall i gciorcail:

```pycon
>>> Reporter.objects.filter(article__reporter__first_name__startswith="John")
<QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
>>> Reporter.objects.filter(article__reporter__first_name__startswith="John").distinct()
<QuerySet [<Reporter: John Smith>]>
>>> Reporter.objects.filter(article__reporter=r).distinct()
<QuerySet [<Reporter: John Smith>]>
```

Má scriosann tú tuairisceoir, scriosfar a n-alt (ag glacadh leis gur sainmhíníodh an ForeignKey le:attr: django.db.models.foreignkey.on\_delete socraithe go `CASCADE`, arb é an réamhshocraithe):

```pycon
>>> Article.objects.all()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
>>> Reporter.objects.order_by("first_name")
<QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>
>>> r2.delete()
>>> Article.objects.all()
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> Reporter.objects.order_by("first_name")
<QuerySet [<Reporter: John Smith>]>
```

Is féidir leat a scriosadh ag baint úsáide as JOIN san fhiosrúchán:

```pycon
>>> Reporter.objects.filter(article__headline__startswith="This").delete()
>>> Reporter.objects.all()
<QuerySet []>
>>> Article.objects.all()
<QuerySet []>
```
