可用于字段集的有序ManyToManyField
我正在处理一个有序的多对多字段小部件,前端部分已经做得很好了:
不过,我在后端的实现上遇到了很多麻烦。连接后端的明显方法是使用一个通过表(through
table),这个表需要与两个关系的模型通过ForeignKey
连接,并且需要重写保存方法。这种方法本来是可行的,但由于内容的特殊性,必须把这个小部件放在一个字段集(fieldset)里(使用ModelAdmin的fieldsets
属性),而这似乎是不可能实现的。
我现在没有其他想法了。有谁能给点建议吗?
谢谢!
1 个回答
关于如何设置模型,你说得对,使用一个带有“顺序”列的中间表是最理想的方式来表示这种关系。你也对,Django 不允许你在字段集中引用这种关系。解决这个问题的关键是要记住,在 ModelAdmin
的“fieldsets”或“fields”中指定的字段名,实际上并不是指 Model
的字段,而是指 ModelForm
的字段,我们可以随意覆盖这些字段。对于多对多字段,这会有点复杂,但请耐心听我解释:
假设你想表示比赛和参赛者之间的关系,其中比赛和参赛者之间有一个有序的多对多关系,顺序表示参赛者在比赛中的排名。你的 models.py
文件可能会是这样的:
from django.db import models
class Contest(models.Model):
name = models.CharField(max_length=50)
# More fields here, if you like.
contestants = models.ManyToManyField('Contestant', through='ContestResults')
class Contestant(models.Model):
name = models.CharField(max_length=50)
class ContestResults(models.Model):
contest = models.ForeignKey(Contest)
contestant = models.ForeignKey(Contestant)
rank = models.IntegerField()
希望这和你正在处理的情况相似。接下来是关于管理后台的部分。我写了一个示例 admin.py
,里面有很多注释来解释发生了什么,但这里有个总结,帮助你理解:
由于我没有你写的有序多对多小部件的代码,我使用了一个占位符的虚拟小部件,它简单地继承自 TextInput
。这个输入框里保存的是一个用逗号分隔的参赛者 ID 列表(没有空格),它们在字符串中的出现顺序决定了它们在 ContestResults
模型中的“排名”列的值。
具体来说,我们覆盖了比赛的默认 ModelForm
,用我们自己的,然后在里面定义了一个“results”字段(我们不能叫这个字段“contestants”,因为那样会和模型中的多对多字段名字冲突)。接着,我们覆盖了 __init__()
方法,这个方法在管理后台显示表单时会被调用,这样我们就可以获取已经为比赛定义的任何 ContestResults,并用它们来填充小部件。我们还覆盖了 save()
方法,这样我们就可以从小部件中获取数据,并创建所需的 ContestResults。
需要注意的是,为了简单起见,这个示例省略了一些内容,比如对小部件数据的验证,所以如果你在文本输入框中输入任何意外的内容,程序可能会出错。此外,创建 ContestResults 的代码相对简单,还有很大的改进空间。
我还要补充的是,我实际上运行过这段代码,并验证它是有效的。
from django import forms
from django.contrib import admin
from models import Contest, Contestant, ContestResults
# Generates a function that sequentially calls the two functions that were
# passed to it
def func_concat(old_func, new_func):
def function():
old_func()
new_func()
return function
# A dummy widget to be replaced with your own.
class OrderedManyToManyWidget(forms.widgets.TextInput):
pass
# A simple CharField that shows a comma-separated list of contestant IDs.
class ResultsField(forms.CharField):
widget = OrderedManyToManyWidget()
class ContestAdminForm(forms.models.ModelForm):
# Any fields declared here can be referred to in the "fieldsets" or
# "fields" of the ModelAdmin. It is crucial that our custom field does not
# use the same name as the m2m field field in the model ("contestants" in
# our example).
results = ResultsField()
# Be sure to specify your model here.
class Meta:
model = Contest
# Override init so we can populate the form field with the existing data.
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
# See if we are editing an existing Contest. If not, there is nothing
# to be done.
if instance and instance.pk:
# Get a list of all the IDs of the contestants already specified
# for this contest.
contestants = ContestResults.objects.filter(contest=instance).order_by('rank').values_list('contestant_id', flat=True)
# Make them into a comma-separated string, and put them in our
# custom field.
self.base_fields['results'].initial = ','.join(map(str, contestants))
# Depending on how you've written your widget, you can pass things
# like a list of available contestants to it here, if necessary.
super(ContestAdminForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
# This "commit" business complicates things somewhat. When true, it
# means that the model instance will actually be saved and all is
# good. When false, save() returns an unsaved instance of the model.
# When save() calls are made by the Django admin, commit is pretty
# much invariably false, though I'm not sure why. This is a problem
# because when creating a new Contest instance, it needs to have been
# saved in the DB and have a PK, before we can create ContestResults.
# Fortunately, all models have a built-in method called save_m2m()
# which will always be executed after save(), and we can append our
# ContestResults-creating code to the existing same_m2m() method.
commit = kwargs.get('commit', True)
# Save the Contest and get an instance of the saved model
instance = super(ContestAdminForm, self).save(*args, **kwargs)
# This is known as a lexical closure, which means that if we store
# this function and execute it later on, it will execute in the same
# context (i.e. it will have access to the current instance and self).
def save_m2m():
# This is really naive code and should be improved upon,
# especially in terms of validation, but the basic gist is to make
# the needed ContestResults. For now, we'll just delete any
# existing ContestResults for this Contest and create them anew.
ContestResults.objects.filter(contest=instance).delete()
# Make a list of (rank, contestant ID) tuples from the comma-
# -separated list of contestant IDs we get from the results field.
formdata = enumerate(map(int, self.cleaned_data['results'].split(',')), 1)
for rank, contestant in formdata:
ContestResults.objects.create(contest=instance, contestant_id=contestant, rank=rank)
if commit:
# If we're committing (fat chance), simply run the closure.
save_m2m()
else:
# Using a function concatenator, ensure our save_m2m closure is
# called after the existing save_m2m function (which will be
# called later on if commit is False).
self.save_m2m = func_concat(self.save_m2m, save_m2m)
# Return the instance like a good save() method.
return instance
class ContestAdmin(admin.ModelAdmin):
# The precious fieldsets.
fieldsets = (
('Basic Info', {
'fields': ('name', 'results',)
}),)
# Here's where we override our form
form = ContestAdminForm
admin.site.register(Contest, ContestAdmin)
如果你在想,我在自己正在做的一个项目中也遇到过这个问题,所以大部分代码来自那个项目。希望你觉得这些内容有用。