简体   繁体   English

停止影响 Django 多对多 model 的其他对象

[英]Stop affecting other objects of Django Many to Many model

I'm trying to replicate Blood Group as Model as defined in this picture.我正在尝试将血型复制为 Model,如此图片中所定义。 血型关系 . .

In my models.py file I had my code to replicate the blood groups like this在我的 models.py 文件中,我有我的代码来复制这样的血型

class BloodGroup(models.Model):
    name = models.CharField(
        max_length=3
    )
    gives = models.ManyToManyField("self")
    receives = models.ManyToManyField("self")

    def __str__(self):
        return self.name

And in my admin.py file I had registered the model as follows在我的 admin.py 文件中,我注册了 model 如下

class BloodGroupAdmin(admin.ModelAdmin):
    model = BloodGroup
    list_display = ['name', 'get_gives', 'get_receives']

    def get_gives(self, obj):
        return ", ".join([item.name for item in obj.gives.all()])

    def get_receives(self, obj):
        return ", ".join([item.name for item in obj.receives.all()])

admin.site.register(BloodGroup, BloodGroupAdmin)

Initially I created plain BloodGroup objects without their gives and receives attribute by providing just their names alone.最初,我通过仅提供它们的名称来创建没有给予和接收属性的普通 BloodGroup 对象。 Thus I create an object for all 8 types.因此,我为所有 8 种类型创建了 object。 Then as I added relationships to each object I found that adding gives or receives for one object affects other objects gives and receives too, making it impossible to replicate the structure in image.然后,当我向每个 object 添加关系时,我发现为一个 object 添加给予或接收也会影响其他对象的给予和接收,因此无法复制图像中的结构。

在此处输入图像描述

  1. How do I define relationships, without affecting other objects?如何在不影响其他对象的情况下定义关系?
  2. In my admin site, I see field names as "get_gives" and "get_receives".在我的管理站点中,我看到字段名称为“get_gives”和“get_receives”。 How would i make the admin page show field names as "gives" and "receives" but still displaying objects as strings like the image below?我如何让管理页面将字段名称显示为“给予”和“接受”,但仍将对象显示为字符串,如下图所示?

For first question , probably it is better to have only one relation gives .对于第一个问题,最好只gives一个关系。 receives can be found from the reverse query .反向查询中可以找到receives Like this:像这样:

class BloodGroup(models.Model):
    name = models.CharField(
        max_length=3
    )
    gives = models.ManyToManyField("self", related_name="receives", symmetrical=False)

Then you only need to add objects to gives .然后你只需要添加对象给gives receives will be generated automatically. receives将自动生成。

For second question , add short_description attribute to function( reference to docs ).对于第二个问题,将short_description属性添加到函数( 参考文档)。 Like this:像这样:

get_gives.short_description = 'Gives'
get_receives.short_description = 'Receives'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM