N
N
Nposk2021-06-21 12:57:36
Django
Nposk, 2021-06-21 12:57:36

How to access related object fields through 2 tables in Django?

There is a database of 4 models (tables), interconnected by a cascade through ForeingKey.
How to get from 1 model to 4 fields and vice versa?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Melnikov, 2021-06-21
@Mi11er

Something like this .. it works the same way =)

class ModelBase(models.Model):
    title = models.CharField(_("Название"), max_length=250, blank=False)

    def __str__(self):
        return self.title


class Model(ModelBase):
    some = models.CharField(_("Что то "), max_length=250)

class Model1(ModelBase):
    some = models.CharField(_("Что то "), max_length=250)
    m = models.ForeignKey(Model, on_delete=models.CASCADE)

class Model2(ModelBase):
    some = models.CharField(_("Что то "), max_length=250)
    m1 = models.ForeignKey(Model1, on_delete=models.CASCADE)

class Model3(ModelBase):
    some = models.CharField(_("Что то "), max_length=250)
    m2 = models.ForeignKey(Model2, on_delete=models.CASCADE)

from core.models import *
m1 = Model.objects.all()
m1[0].model1_set
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x00000296EFFAAE20>

m1[0].model1_set.all()[0].model2_set.all()[0].model3_set.all()[0].some
'some m3'

M
Misha Tarasov, 2021-06-22
@Miha_Tarasov

Let's imagine 2 models Post and Category . In the Post model, a field with a relationship (let's call this field cat ) is foreignkey with Category (i.e. Post is a secondary model, Category is a primary). If we want to refer to Category: through the Post model . There was an example of filtering posts that have a category with id=1. That is, we are looking for posts whose category is the very first (by id). If we want to access the Post model (feedback) through the Category , then we need to use the feedback manager ( [secondary model name] _set or use the related_name property, if it is defined on the field cat ). For example:Post.objects.filter(cat__id=1)

cat = Category.objects.get(id=1) - получение категории с  id=1

And now through the feedback manager (in our case, if related_name is not specified, it will be post_set, but if related_name is specified, use it). cat.post_set.all() - display all posts belonging to cat, category with id =1. I hope I explained what needs to be explained.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question