Django:在表单中保存多对多。

时间:2022-10-04 16:05:55

I got such models:

我有这样的模型:

Guests:

客人:

class Guest(models.Model):
    name = models.CharField(max_length=255)
    phone = models.CharField(max_length=255)
    # ...

and meetings:

和会议:

class Meeting(models.Model):
    # some fields ...
    guests = models.ManyToManyField(through='GuestOnMeeting')

A lot of guests can be in a meeting. And one guest can attend many meetings. And we are to store some additional information in relation. So, it is many-to-many through some model.

很多客人可以参加会议。一个客人可以参加很多会议。我们将储存一些相关的额外信息。通过一些模型,它是多对多的。

class GuestOnMeeting(models.Model):
    guest = models.ForeignKey(Guest)
    meeting = models.ForeignKey(Meeting)

    # ... some other fields

The questions are:

的问题是:

  1. How do I define a form to edit meeting's guest list (invite guests - later we will use it to send sms-invitations - no spam, the guest are almost our friends;) ).

    我如何定义一个表单来编辑会议的客人列表(邀请客人——稍后我们将用它发送sms邀请——没有垃圾邮件,客人几乎是我们的朋友)。

  2. Every Guest has a manager (manager = models.ForeignKey(Managers)). How can I modify this form (or these models) to allow managers to invite only guests linked to them (with the foreign key)?

    每个客人都有一个经理(经理=模特。我如何修改这个表单(或这些模型)以允许经理只邀请与它们相关的客户(使用外键)?

1 个解决方案

#1


2  

If you want something like the admin inlines, you are looking for inlineformset_factory.

如果您想要一些类似于admin inlines的东西,那么您正在寻找inlineformset_factory。

>>> from django.forms.models import inlineformset_factory
>>> GuestOnMeetingInline = inlineformset_factory(GuestOnMeeting, Meeting)
>>> meeting = Meeting.objects.all()[0]
>>> form = MeetingForm(instance=meeting)
>>> formset = GuestOnMeetingInline(instance=meeting)

You can add fields or pass custom forms and/or querysets to modelformset_factory.

可以向modelformset_factory添加字段或传递自定义表单和/或查询集。

#1


2  

If you want something like the admin inlines, you are looking for inlineformset_factory.

如果您想要一些类似于admin inlines的东西,那么您正在寻找inlineformset_factory。

>>> from django.forms.models import inlineformset_factory
>>> GuestOnMeetingInline = inlineformset_factory(GuestOnMeeting, Meeting)
>>> meeting = Meeting.objects.all()[0]
>>> form = MeetingForm(instance=meeting)
>>> formset = GuestOnMeetingInline(instance=meeting)

You can add fields or pass custom forms and/or querysets to modelformset_factory.

可以向modelformset_factory添加字段或传递自定义表单和/或查询集。