user9341676
user9341676

Reputation: 61

How can I access column in model?

How can I access income in NewUser model? I wanna filter Car model's data by user's income data.My ideal system is car name is shown in car.html if NewUser's income = Car income. I wrote in models.py

class NewUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    income = models.CharField(max_length=20, null=True, default=None)

class Car(models.Model):
    name = models.CharField(max_length=100, null=True, default=None)
    income = models.CharField(max_length=20, null=True, default=None)

in views.py

from app.models import Car
from django.shortcuts import render

def car(request):
    car_data = Car.objects.all().filter(income=request.user.income)
    return render(request, 'car.html', {'car_data': car_data})

When I access car method,AttributeError at /app/car/ 'User' object has no attribute 'income' error happens.I really cannot understand why such a error happens.I inherit User model in NewUser,so I think I can access income in request.user.How should I fix this?What is wrong in my codes?

Upvotes: 0

Views: 42

Answers (1)

Dalvtor
Dalvtor

Reputation: 3286

You get that error because the User table doesn't have an income column. It is the NewUser model which has it. Since there is a OneToOneField between NewUser and User, all you need to do:

car_data = Car.objects.all().filter(income=request.user.newuser.income)

Also, you state that you inherit User model in NewUser, but that is not true, NewUser inherits models.Model.

Upvotes: 1

Related Questions