Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to connect 2 many to many fields in Django

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading