[英]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 添加给予或接收也会影响其他对象的给予和接收,因此无法复制图像中的结构。
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.