D
D
dmitriystrel002021-05-03 20:12:42
Django
dmitriystrel00, 2021-05-03 20:12:42

How to correctly select a record from a database with an exact set of relationships?

For example:

# models.py
class Tag(models.Model):
    name = models.CharField()
    content = models.ManyToManyField('Content', through='TagContent')

class Content(models.Model):
    title = models.CharField()
    description = models.TextField()
    tags = models.ManyToManyField('Tag', through='TagContent')

class TagContent(models.Model):
    tag = models.ForeignKey('Tag', on_delete=models.CASCADE)
    content = models.ForeignKey('Content', on_delete=models.CASCADE)


DB:
-----------------
Tag:
- 1 | One
- 2 | Two
-----------------
Content:
- 1 | One
- 2 | One and Two
- 3 | Two
-----------------
TagContent:
- 1 | 1
- 1 | 2
- 2 | 2
- 2 | 3

The question itself:
How to correctly select a record with the exact set of relationships from the Content table?
That is, if I choose this way:
Content.objects.filter(tags__id=1)
I will get content 1 and 2, but I need only 1.
Accordingly, if tags__id=2, I will get content 2 and 3, but I need 2, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deleting Account, 2021-05-03
@Andriy_Kosmenyuk

Try it through the get method, I don’t know for sure, I didn’t even remember about django for 2 years. And so, in the docs, I think it's not difficult to find the answer to your question https://docs.djangoproject.com/en/3.2/topics/db/models/ . There should not be a question, the answer to which can be obtained by reading the technology documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question