在Admin或View中自引用对称的多对多Django模型

时间:2018-07-09 23:22:13

标签: django django-models many-to-many django-orm

如何在M2M Django模型中获得对称自参考的另一面?

假设我们正在制作零件目录,并且有很多Part,并且我们希望有一个Interchange来显示哪些零件可以代替另一个零件:

class Part(models.Model):
    name = models.CharField(max_length=300)
    number = models.CharField(max_length=200, default 'because numberphiles like more ids')
    …
    interchanges = models.ManyToManyField("self",
                                          through='Interchange',
                                          symmetrical=False,
                                          # + sign per http://charlesleifer.com/blog/self-referencing-many-many-through/
                                          # I have tried without the plus t omaintain the references as well, but can't seem to understand the difference(s)
                                          related_name="interchanges_to+",
                                          # through_fields per docs
                                          through_fields=('reference', 'interchange')
                                          )

    # per this http://charlesleifer.com/blog/self-referencing-many-many-through/
    def add_interchange(self, part, symm=True):
        interchange = models.Interchange.objects.get_or_create(
            reference_part=self,
            interchange_part=part)
        if symm:
            # avoid recursion by passing `symm=False`
            part.add_interchange(self, False)
        return interchange

    def remove_interchange(self, part, symm=True):
        models.Interchange.objects.filter(
            reference_part=self,
            interchange_part=part).delete()
        if symm:
            # avoid recursion by passing `symm=False`
            part.remove_interchange(self, False)

    def get_interchanges(self):
        return ", ".join([str(p) for p in self.interchanges.filter(interchange_part__reference=self)])

    def get_references(self):
        return …?
        # This is where I don't know how to get the Parts that are referring to it as being an interchange

class Interchange(models.Model):
    reference = models.ForeignKey(Part, related_name="reference_part")
    interchange = models.ForeignKey(Part, related_name="interchange_part")
    # just to confirm we have a M2M table, we will add a foregin key to a User if this interchange has been personally verified
    confirmed_by = models.ForeignKey(User, null=True, blank=True)
    # … others if needed

    class Meta:
        # because self-referencing, in this case, is silly, we make sure each part references another part
        unique_together = ('reference', 'interchange')

在Django管理员中,我有:

@admin.register(app.Part)
class PartAdmin(admin.ModelAdmin):
    list_display = ['name', 
                    'number', 
                     # ▼ I can see the Parts itself Interchanges to
                    'get_interchanges', 
                     # ▼ I can not see the Parts that reference itself as being an Interchange
                    'get_references'] 

管理员中的零件模型以供参考...

这是我所拥有的: Current Models without symmetrical references

这就是我想要得到的: What I am trying to get with symmetrical references

作为确认,管理员中的交换模型: Interchange Model

如何获得对称自参考M2M Django模型的另一面?
如何返回交换表中但在引用(第一)列中的Part

注意:

  • 使用django 1.11
  • 我知道根据docs通过模型使用M2M时,要求对称性为False
  • This不错的文章帮助我取得了很大的进步,但是在管理员中,我似乎无法让interchange_part在管理员页面上显示其reference_part(因此,我什至没有尝试过查看具有不同/特定功能的视图是否可能)
  • docs中,它表示through_keys的元组的第二部分称为target模型,但是我找不到要引用第一个的元组
  • 我确信有一种方法可以深入多层次,即如果第一部分交换为2,而2 => 3,则1应该列出2和3(但目前不是重点)
  • 请纠正我的误会,谢谢:)

1 个答案:

答案 0 :(得分:0)

如果manytomany具有一个带有related_name参数的穿透表,并且不包含+,那么您可以直接访问该集合:

def get_references(self):
    return ", ".join([str(p) for p in self.interchanges_to.all()])

注意,我不确定性能/复杂度