How to connect 2 many to many fields in Django

Question:

I have 2 many to many fields in models and i want to connect them to each other i mean if i connect user in Admin Model with Counter Party i cant see that in Counter Party admin

How can i do that?

When im trying to do that it shows only in 1 model

models.py

class CustomUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь')
    user_counter = models.ManyToManyField('CounterParty', blank=True, verbose_name='Контрагенты пользователя')

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


class CounterParty(models.Model):
    GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
    name = models.CharField(max_length=150, verbose_name='Наименование')
    customer = models.BooleanField(default=False, verbose_name='Заказчик')
    contractor = models.BooleanField(default=False, verbose_name='Подрядчик')
    counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user',
                                          verbose_name='Пользователи контрагента')

    class Meta:
        verbose_name = 'Контрагент'
        verbose_name_plural = 'Контрагенты'

    def __str__(self):
        return

admin.py

from django.contrib import admin
from .models import CustomUser, CounterParty, ObjectList, SectionList
from authentication.models import User
from authentication.admin import UserAdmin


class CustomUserInLine(admin.StackedInline):
    model = CustomUser
    can_delete = False
    verbose_name_plural = 'Пользователи'


class CustomUserAdmin(UserAdmin):
    inlines = (CustomUserInLine,)


@admin.register(CounterParty)
class CounterPartyAdmin(admin.ModelAdmin):
    pass


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)


user admin

counter party admin

Asked By: Zesshi

||

Answers:

You would not want to have these kinds of references with ManyToMany. Ideally you would have a one sided reference.

You can do an inline in your admin like this:

class CustomUserInLine(admin.StackedInline):
    model = "CustomUser.user_counter.through"

Here are the docs for inline M2M in the admin: Django docs

Answered By: user20223018
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.