Ashish Kumar Verma
Ashish Kumar Verma

Reputation: 1368

How to use Django Queryset efficiently

I have three models in Django, One is default django user model.

class ConfigurationDB(models.Model):
    project_id = models.CharField(max_length=250)

    def __unicode__(self):
        return str(self.project_id)


class ProjectAssociated(models.Model):
    user_name = models.ForeignKey(User, verbose_name="User Name")
    configuration = models.ManyToManyField(ConfigurationDB, verbose_name= "Project Associated")

    def __unicode__(self):
        return str(self.user_name)

I got username from the url, I want to write a Django Query to get the project Associted with that user, and store in a list.

Upvotes: 1

Views: 94

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174728

First, you should fetch a user object, to make sure that the username passed actually exists. Then, query directly by that user object.

from django.shortcuts import get_object_or_404, render

def your_view(request, username=None):
   user = get_object_or_404(User, username=username)
   pa = ProjectAssociated.objects.filter(user_name=user)

   return render(request, 'template.html', {'projects': pa})

Upvotes: 1

Dhia
Dhia

Reputation: 10619

Do Simply:

ProjectAssociated.objects.filter(user_name__username=username)

And you don't need any additional work to store it in list, filter by default return a List.

Tipp: in relation such as ForeignKey it's better to use related_name attribute as follow:

user_name = models.ForeignKey(User,verbose_name="User Name", related_name="associated_projects")

this can be useful in case you have the user instance you can access the reverse the relation directly:

user1 = User.objects.get(username=username_value) # here all the user data
associated_project_list = user1.associated_projects.all() # here the list of his projects

to access a project id you need simply:

for project in associated_project_list:
    print project.id

Upvotes: 0

Geo Jacob
Geo Jacob

Reputation: 6009

Try this;

pa = ProjectAssociated.objects.filter(user_name__username=username)

And to get all configuration;

configuration = pa.configuration.all()

Here you will get the queryset of configuration and if you want only the list of project_id, then you can try this;

configuration = pa.configuration.all().values_list('project_id', flat=True)

Upvotes: 1

Related Questions