Answer the question
In order to leave comments, you need to log in
How to write data from another field into a ManyToMany field automatically?
There is a 'Project' model with 'managers' and 'members' fields, which have a ManyToManyField field type .
I'm trying to make it so that when filling in the 'managers' field, the records from this field are automatically duplicated or recorded in the 'members' field. I display only the 'managers' field in the admin panel. After creating the Project object, the 'members' field is empty in the database. How can this problem be solved? Here's what I've done so far:
models.py :
class Project(models.Model):
***
managers = models.ManyToManyField(User, related_name='managers')
members = models.ManyToManyField(User, related_name='members')
def save(self, *args, **kwargs):
if self.id:
for manager in self.managers.all():
if manager not in self.members.all():
self.members.add(manager)
super(Project, self).save(*args, **kwargs)
class ProjectAdminForm(ModelForm):
class Meta:
model = Project
fields = 'managers'
def clean(self):
members = self.cleaned_data['members']
managers = list(self.cleaned_data['managers'])
for manager in managers:
if manager not in members:
members.append(manager)
self.cleaned_data['members'] = members
return self.cleaned_data
class ProjectAdmin(admin.ModelAdmin):
model = Project
form = ProjectAdminForm
admin.site.register(Project, ProjectAdmin)
Answer the question
In order to leave comments, you need to log in
There is no need to duplicate
There are several solutions
- make a method in the model to display members + managers
class Project(models.Model):
# ***
def members_dict(self):
return { 'basic_members': self.members, 'managers': self.managers}
class ProjectMembers(models.Model):
member = ForeignKey(Member)
progect = ForeignKey(Progect)
is_manager = BooleanField(default=False)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question