Search code examples
pythondjango-modelsmany-to-many

Django: Get related objects in many to many relationship


I am writing to ask for your help with my Django project. I have created a database that contains data for Master and Subcategories, but I am struggling to retrieve the related records. In particular, I am looking for a Master ID - Sub ID relationship.

class Categories(models.Model):
    cat_id = models.AutoField(primary_key=True)
    cat_name = models.CharField(max_length=200, help_text='Добавь новую категорию')

    def __str__(self):
        return f'{self.cat_name}'


class Subcategories(models.Model):
    sub_id = models.AutoField(primary_key=True)
    sub_cat = models.ForeignKey(Categories, on_delete=models.CASCADE,)
    sub_name = models.CharField(max_length=200, help_text='Добавь новую подкатегорию')

    def __str__(self):
        return f'{self.sub_cat} {self.sub_name}'


class Masters(models.Model):
    master_id = models.AutoField(primary_key=True)
    sub_master = models.ManyToManyField(Subcategories)
    name = models.CharField(max_length=200, help_text='Имя')
    info = models.CharField(max_length=500, help_text='Дополнительная информация', default=None, null=True, blank=True)
    phone = models.CharField(max_length=10, help_text='Контактный номер телефона', default=None, null=True, blank=True)
    address = models.CharField(max_length=500, help_text='Адрес, при наличии', default=None, null=True, blank=True)
    tg = models.CharField(max_length=20, help_text='Ник или ссылка на telegram', default=None, null=True, blank=True)
    wa = models.CharField(max_length=20, help_text='Ник или ссылка на whatsapp', default=None, null=True, blank=True)
    ig = models.CharField(max_length=20, help_text='Ник или ссылка на instagram', default=None, null=True, blank=True)
    vk = models.CharField(max_length=20, help_text='Ник или ссылка на vk', default=None, null=True, blank=True)
    password = models.CharField(max_length=20, editable=False, unique=True)
    visability = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.master_id}, {self.sub_master}, {self.name}, {self.phone}, {self.address}, {self.tg}, ' \
               f'{self.wa}, {self.ig}, {self.visability}, {self.password},({", ".join(subcategories.sub_name for subcategories in self.sub_master.all())})'

II have tried a number of options, including reading the documentation and searching for answers on forums, but none of them have helped me. Here are the options that I have considered:

  • Masters.subcategories_set.through.objects.filter(master_id=12)

AttributeError: type object 'Masters' has no attribute 'subcategories_set'

  • AttributeError: type object 'Masters' has no attribute 'subcategories

AttributeError: type object 'Masters' has no attribute 'subcategories'

master = Masters.objects.get(master_id=12)
        objects = master.sub_master.all()

<QuerySet [<Subcategories: Test2 test2>]> This option simply returns the names of the subcategories and masters objects, but I need associated IDs in the masters - subcategories relationships.

I feel like I'm missing something obvious, but I just can't seem to figure out what it is.


Solution

  • master = Masters.objects.get(master_id=pk)
    s_m = master.sub_master.all()
    connected_subs = []
    for sub in s_m:
        connected_subs.append(sub.sub_id)
    

    I found the answer