我无法为我认为是初学者的问题找到合适的解决方案。我们非常感谢您的帮助。
我正在建立的网站将用于计划聚会。有两种类型的人可以使用它:聚会组织者和聚会访客。 派对组织者可以创建一个派对并选择要提供给访问者的项目。项目是食物和饮料,一项=一份比萨饼或一份啤酒。
然后,用户将能够确认该聚会的参与,并选择他们想要订购的食物和饮料以及数量。 我已经创建了身份验证和创建了聚会。
现在,我的问题是这样:
我尝试使用以下代码(已整理):
models.py:
class ItemType(models.Model):
"""Create items (food and drinks)."""
name = models.CharField()
class Party(models.Model):
"""Create a party."""
organizer = models.ForeignKey(User)
party_name = models.CharField()
items_to_be_offered = models.ManyToManyField(ItemType)
class PartyRegistration(models.Model):
"""Register for a party / create party registration."""
party = models.ForeignKey(Party)
visitor = models.CharField()
selected_items = models.ManyToManyField()
class ItemSelection(models.Model):
"""Specify which items and number of items the visitor selected."""
party_registration = models.OneToOneField(PartyRegistration)
item_type = models.ManyToManyField(ItemType)
item_quantity = models.PositiveIntegerField()
forms.py
class VisitorRegisterForm(forms.ModelForm):
"""Form to register a visitor."""
class Meta:
model = PartyRegistration
fields = ['visitor', 'selected_items']
views.py
def VisitorRegister(request, pk):
"""Register Visitor to a specific party."""
party = get_object_or_404(Party, pk=pk)
if request.method == 'POST':
form = VisitorRegisterForm(request.POST)
if form.is_valid():
name_clean = form.cleaned_data['visitor']
registration = PartyRegistration(party=party, visitor=name_clean)
registration.save()
return HttpResponseRedirect(reverse('index'))
else:
form = VisitorRegisterForm()
context = {'form': form, 'party': party}
return render(request, 'visitor-register.html', context)
网站是Django 2.0,PostgreSQL。
答案 0 :(得分:0)
在这种情况下,您需要使用through
模型与ManyToMany关系(顺序很重要,或更改顺序并引用PartyRegistration
):
class PartyRegistration(models.Model):
"""Register for a party / create party registration."""
party = models.ForeignKey(Party)
visitor = models.CharField()
selected_items = models.ManyToManyField(ItemType, through='ItemSelection')
class ItemSelection(models.Model):
"""Specify which items and number of items the visitor selected."""
party_registration = models.ForeignKey(PartyRegistration)
item_type = models.ForeignKey(ItemType)
item_quantity = models.PositiveIntegerField(default=1)
class Meta:
unique_together = ('party_registration', 'item_type')
请参见https://docs.djangoproject.com/en/2.1/topics/db/models/#intermediary-manytomany