Home > Blockchain >  getting error with _set in Django Query-Set, object has no attribute
getting error with _set in Django Query-Set, object has no attribute

Time:09-18

I use _set to make ManyToMany relationship between customer and Service but endup having Error:

AttributeError at /customer/1/
'carOwner' object has no attribute 'serviceOrderX_get'

Is there anyone who want to help me..

models.py

...

class carOwner(models.Model):
    name_X = models.CharField( max_length=150, null=True)
    email_X = models.CharField( max_length=150, null=True)
    phoneNo_X =models.CharField( max_length=150, null=True)

    def __str__(self):
        return self.name_X

class serviceOrderX(models.Model):
    CATEGORES = (...)
    carName_X = models.CharField( max_length=150, null=True)
    carNO_X = models.CharField( max_length=150, null=True)
    carOwner_X = models.ManyToManyField(carOwner)
    catagores_X = models.CharField(max_length=200,null=True,choices=CATEGORES)
    price_X = models.IntegerField(  null=True)
    service_X = models.ManyToManyField(orderService)

    def __str__(self):
        return str(f'{self.carName_X} , {self.carNO_X}')

views.py

...

def CustomerX(request , pk):
    customersX = carOwner.objects.get(id=pk)
    cuter = customersX.serviceOrderX_set.all()

    contX = {
        'customer' : cuter , 
    }
    return render(request, 'customer.html' , contX)

CodePudding user response:

If you want to relate field, the first argument you should add is name of model you want to relate. In your case you can fix this

class serviceOrderX(models.Model):
    # change here
    service_X = models.ManyToManyField(carOwner)

read more here: https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

CodePudding user response:

I think you just have a typo in your code. It should be set instead of get -> customersX.serviceOrderX_set.all()

See https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

You can also set a related_name on your ManyToManyField like service_orders so that you can do customersX.service_orders.all()

Btw. just a hint, using camel case for your fields in python is not a good style. Just do car_owner_x and for your class names use eg ServiceOrderX

See: https://peps.python.org/pep-0008/

  • Related