Home > front end >  AttributeError: 'ManyRelatedManager' object has no attribute 'log_order'
AttributeError: 'ManyRelatedManager' object has no attribute 'log_order'

Time:09-19

I have the following model classes with many to many relations and I am trying to loop through the query to find if there is a match in one of the fields log_order but I keep getting AttributeError: 'ManyRelatedManager' object has no attribute 'log_order':

To get a better idea here is the model:

class Log(models.Model):
    ...................................
    log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True)
    date = models.DateTimeField(...........)

class LogForm(forms.Form):
    .............................
    log_order = forms.IntegerField()

class ActiveSession(models.Model):
    log = models.ManyToManyField(Log)
    ..................................

In my views I am trying to get the data in the form and saving in the log model which is currently working fine. My next step is to loop through the ActiveSession.log to check if the log_order is available to just update it instead of adding a new log to the session.

Here is the views:

def addlog(request, id):
    url = request.META.get('HTTP_REFERER')  # get last url
    active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id)

    if request.method == 'POST':  # check post
        form = LogForm(request.POST)
        if form.is_valid():
            data = Log()
            data.log_order = request.POST.get('log_order')
            data.save()  # save data to table
            active_session.log.add(data)
            print('Log added to Session')
            # for i in active_session.log.log_order:
            #     print(i)
            #
            # for i in active_session.log.log_order.all():
            #     if data.log_order == i:
            #         print("Available in Active Session")
            #     else:
            #         active_session.log.add(data)
            #         print('log added in session')
            return HttpResponseRedirect(url)
    return HttpResponseRedirect(url)

My outcome required: When the Post is valid and successful to loop through the logs inside the activesession and if the log_order is available to replace the existing if not available to be added.

I have commented my trials as they returned errors.

CodePudding user response:

for i in active_session.log.all():
    if i.log_order == 1 // this is your data response:
        print(i)

Or you can use .values()

so if you use:

for i in active_session.log.values() 

you get a queryset where you do your if then stuff.

<QuerySet [{'id': 1, 'log_order': 1}]>
  • Related