如何在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']
管理员中的零件模型以供参考...
如何获得对称自参考M2M Django模型的另一面?
如何返回交换表中但在引用(第一)列中的Part
注意:
答案 0 :(得分:0)
如果manytomany具有一个带有related_name
参数的穿透表,并且不包含+
,那么您可以直接访问该集合:
def get_references(self):
return ", ".join([str(p) for p in self.interchanges_to.all()])
注意,我不确定性能/复杂度