【问题标题】:Django ManytoMany not showing in adminDjango ManytoMany 未在管理员中显示
【发布时间】:2020-05-09 08:17:54
【问题描述】:

由于我的模型是多对多关系,所以连接应该是双向的,但不是。

例如,在BusinessProfile 部分的管理员中,我可以看到Services 模型的名称和图像字段,因为它们处于多对多关系中,但相反的情况并非如此。我无法在管理员的Services 模型中看到BusinessProfile 模型字段。

我的模型结构正确吗?

我还附上了图片。

模型.py

class Service(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='image', blank = True)
    #business_profile = models.ManyToManyField("BusinessProfile", blank=True, related_name="business_of_services")

    def __str__(self):
        return "Service - {}".format(self.name)


class BusinessProfile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
    business_name = models.CharField(max_length=100, unique =True)
    register_date = models.DateTimeField(default=timezone.now)
    pan_number = models.IntegerField(unique=True)
    pan_name = models.CharField(max_length=100)
    address = models.TextField(max_length=200)
    pincode = models.IntegerField()
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50)

    service  = models.ManyToManyField("Service", blank=True, related_name="services_of_business")
    image  = models.ManyToManyField("Service", related_name="image_of_business")

    def __str__(self):
        return "Business - {}".format(self.business_name)

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    如果你想使用反向多对多管理,你可以使用内联。见this document

    文档中的示例代码。

    from django.contrib import admin
    
    class MembershipInline(admin.TabularInline):
        model = Group.members.through
    
    class PersonAdmin(admin.ModelAdmin):
        inlines = [
            MembershipInline,
        ]
    
    class GroupAdmin(admin.ModelAdmin):
        inlines = [
            MembershipInline,
        ]
        exclude = ('members',)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2019-08-12
      • 2021-08-14
      • 2010-11-21
      • 2016-05-27
      • 1970-01-01
      • 2017-05-08
      相关资源
      最近更新 更多