gpt4 book ai didi

django - 如何通过直通关系保存ManyToMany字段

转载 作者:行者123 更新时间:2023-12-04 13:13:12 26 4
gpt4 key购买 nike

我有以下具有ManyToManythrough关系的模型:

class Meeting(models.Model):
site = models.ForeignKey(Site)
meeting_title = models.CharField(default='', max_length=128, blank=True, null=True)
meeting_visitors = models.ManyToManyField(Visitor, through="MeetingArrival", blank=False, null=False)

class Visitor(models.Model):
visitor_company = models.ForeignKey(Company)
visitor_name = models.CharField(default='', max_length=128, blank=False, null=False)

class MeetingArrival(models.Model):
visitor = models.ForeignKey(Visitor)
meeting = models.ForeignKey(Meeting)
arrival_status = models.BooleanField(default=False)

我有一个创建 session 的表格:
class AddMeetingForm(forms.ModelForm):

class Meta:
model = Meeting
exclude = ['site',]

和一个简单的 View 来保存表单:
def add_meeting(request): 
add_meeting_form = AddMeetingForm(request.POST or None)
site = Site.objects.get(user=request.user.id)

if request.method == "POST":
if add_meeting_form.is_valid():

obj = add_meeting_form.save(commit=False)
obj.site = site
obj.save()

即使该字段在 View 中完美呈现,这也会保存表单,但不会保存 meeting_visitors字段。如何保存这种关系?

编辑

如果将 add_meeting_form.save_m2m()添加到 View 中,则会得到 Cannot set values on a ManyToManyField which specifies an intermediary model. Use meetings.MeetingArrival's Manager instead.。我该怎么做?

最佳答案

您必须在 View 中显式保存MeetingArrival对象,以在使用ManyToManyField参数的through情况下保存中间模型。
对于Django 2.1及更低版本,如果ManyToManyField具有中间模型,则不能使用通常用于多对多字段的addcreateassignment
按照Django 1.8 docs:

Unlike normal many-to-many fields, you can’t use add, create, orassignment to create relationships.

The only way to create this type of relationship is to createinstances of the intermediate model.


因此,您将必须在 View 中显式创建一个 MeetingArrival对象。
您可以通过以下方式做到这一点:
def add_meeting(request): 
add_meeting_form = AddMeetingForm(request.POST or None)
site = Site.objects.get(user=request.user.id)

if request.method == "POST":
if add_meeting_form.is_valid():
obj = add_meeting_form.save(commit=False)
obj.site = site
obj.save()

# create an instance of 'MeetingArrival' object
meeting_arrival_obj = MeetingArrival(meeting=obj, visitor=<your_visitor_object_here>, arrival_status=True)
meeting_arrival_obj.save() # save the object in the db

关于django - 如何通过直通关系保存ManyToMany字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31862599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com