sajal garg
sajal garg

Reputation: 139

Django Manytomany add

I have 2 models in my Project with Many to Many relationship. On saving model Event, I read from the event_attendees file and add it to the attendees field in the Event. No errors/exceptions shown but attendee is not added to the attendees field. Do I need to save the model again after altering with the attendees field? If so, how to do that (calling save method from add_attendees will cause the program into infinite loop)?

class Attendee(models.Model):
    name = models.CharField(max_length=100)

class Event(models.Model):
    name = models.CharField(max_length=100)
    event_attendees = models.FileField(upload_to='documents/', blank=True)
    attendees = models.ManyToManyField(Attendee, blank=True)

    def save(self, *args, **kwargs):
        super().save()
        self.add_attendees()           

    def add_attendees(self):
        with open(self.event_attendees.url[1:]) as csv_file:
            # Some code here
            for row in csv_reader:
                        # Some code here
                        attendee = Attendee(name=name)
                        attendee.save()
                        self.attendees.add(attendee)
                        print(self.attendees.all())     # attendee added
                        print(attendee.event_attended)  # event present with attendee
                        #Refresh template to check changes -> Changes lost

Upvotes: 0

Views: 200

Answers (2)

sajal garg
sajal garg

Reputation: 139

Apparently, the feature worked when I used non-admin web dashboard. While using by-default-created /admin dashboard, this feature was not working. I am assuming from the results that the admin side code calls different methods while saving the model object even though I have overridden the save method (and hence my save method along with other methods should be called). I will update with more info if I find it.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

It's the Attendee object that you haven't saved.

You can shortcut it by using the create method on the m2m field:

for row in csv_reader:
    self.attendees.create(name=whatever)

(Note, please don't blindly catch exceptions. Django will already do that and report a useful error page. Only catch the exceptions you are actually going to deal with.)

Upvotes: 1

Related Questions