Home > Software design >  How i can get a value field from a foreignkey field properly
How i can get a value field from a foreignkey field properly

Time:03-11

i want to get a value field (named "width") from foreignkey field named square(last selectable choice by the user) exist on my form:

Here is the code line that i have used it to get this value("width"):

width = float(FormulaireIng.objects.get(square = FormulaireIng.objects.last()).values_list('width'))

Here is the models.py:

class FormulaireIng(models.Model): 
    square = models.ForeignKey(Square, on_delete=models.CASCADE)

class Square(models.Model): 
    width = models.FloatField(verbose_name="Width", max_length=50)

an error displayed after developing that:

ValueError at /pdf/
Cannot query "4.0": Must be "Square" instance.

How i can get a value field from a foreignkey field properly from a model.

Thanks in advance.

Edited the function where am trying to get on it the field value "width" from the model:

def forms_render_pdf_view(request, *args, **kwargs):   
    template_path = 'pdf.html'  
    width = float(FormulaireIng.objects.get(square = 
    FormulaireIng.objects.last()).values_list('width'))
    design = (2/8) / width
    context = {'design': design}

CodePudding user response:

Try this again. Should work now

formulaire_object = FormulaireIng.objects.all().last()
square = formulaire_object.square
width = square.width

CodePudding user response:

The error shows clearly what the problem is. It should be a Square instance and not FormulaireIng instance. You're looking for 'width' which is in Square model, so how about querying the Square model directly. You can pass in the id of the square object and get the width.

width = Square.objects.get(id=id).width

CodePudding user response:

If you want to get the width for the last foreign key field in the Formulaireing model then..

width = FormulaireIng.objects.all().last().width
  • Related