Checked all docs and questions/answers here but not succesfull. Need your help. I've experience in pure PHP and MySQL, but frameworks kills me.
My models;
class Projects(models.Model):
id = models.AutoField(primary_key=True)
subject= models.CharField(max_length=50)
sender= models.ForeignKey(User, on_delete=models.CASCADE)#inserting django's default user id
This is django's default but edited auth_user
table
CREATE TABLE "auth_user" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "is_superuser" bool NOT NULL, "username" varchar(150) NOT NULL UNIQUE, "first_name" varchar(150) NOT NULL, "last_name" varchar(150) NOT NULL, "email" varchar(254) NOT NULL, "is_staff" bool NOT NULL, "is_active" bool NOT NULL, "date_joined" datetime NOT NULL, "tck_no" varchar(11) NOT NULL )
When I want to fetch my project, I use normally;
SELECT u.*, p.* FROM users u, projects p WHERE u.id=p.sender;
Above code returns all fields on both table normally.
In django viewmodel;
@login_required(login_url="/login/") def others_projects(request): projectlist = Projects.objects.all().filter(sender_id=request.user.id)
Above code returns Projects table fields, but can not figured how to get first_name field matched record from users foreign key used?
CodePudding user response:
If you are iterating through your projectlist
you could access it as such.
projectlist = Projects.objects.filter(sender=request.user)
for p in projectlist :
print(f'First name is {p.sender.first_name}')
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#filter
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/