Home > Software design >  How to correctly write a condition in view Django?
How to correctly write a condition in view Django?

Time:06-22

The meaning of the program is to select analogues from the list and link them. I bind all values. I think the problem is in the wrong if. How to fix it

My view:

def editpart(request, id, **kwargs):

    if request.method == 'POST':
        part.name = request.POST.get("name")
        part.description = request.POST.get("description")

        analogs = Part.objects.all()
        for analog_zap in analogs:
            analog = analog_zap.analog
                if Part.objects.filter(analog_analog = analog):
                        part.analog.add(analog_zap.id)

My model:

class Part(models.Model):
    name = models.CharField('Название', max_length=100)
    analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts')

CodePudding user response:

I'm just going to assume you have gotten a part object before trying to assign the following:

part.name = request.POST.get("name")
part.description = request.POST.get("description")

Whether this was intended to update the "retrieved part object" or not, I'd recommend that you have instead two fresh variables to collect the info from the post request, then update the part object with these if any related info were found in the database.

name = request.POST.get("name")
description = request.POST.get("description")

As for the real issue here... Not sure I'm understanding your question much but I do see a problem with one of your if statements though. You have:

for analog_zap in analogs:
     analog = analog_zap.analog
          if Part.objects.filter(analog_analog = analog):  # problem here...
               part.analog.add(analog_zap.id)

As you've posted:

class Part(models.Model):
     name = models.CharField('Название', max_length=100)
     analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts')  # right here...

The Part model has a field called analog, not analog_analog: maybe you meant analog__analog. But maybe you should try checking by: if Part.objects.filter(analog__pk=analog.pk) or if Part.objects.filter(analog__in=[analog]).distinct().

Furthermore, what you might want to do is to check if something exists, so add .exists() to the end of if Part.objects.filter(analog__pk=analog.pk). Example:

if Part.objects.filter(analog__pk=analog.pk).exists():
     ...

Looking like:

for analog_zap in analogs:
     analog = analog_zap.analog
          if Part.objects.filter(analog__pk=analog.pk).exists():
               part.analog.add(analog_zap.id)
               
               # update the name and description here as well with the values retrieved from the post request
               part.name = name
               part.description = description

You could try that.

  • Related