Reputation: 2797
I'm new to django and have the following model:
class MainFile(models.Model):
owner = models.ForeignKey(User)
# docfile = models.FileField(verbose_name= 'Enter you file', null=True)
file_id = models.UUIDField(max_length=38, primary_key=True, default=1)
file_name = models.CharField(max_length=70)
file_suffix = models.CharField(max_length=5, blank=True, null=True)
file_date = models.DateTimeField(auto_now_add=True, null=True)
So I want to filter a row of the table using file_id, and having that row, access the file_suffix. Currently I've found the following way but it's tricky:
obj = MainFile.objects.filter(file_id = 'e3e978a3-0375-4bb9-85a2-5175e2ec097d')
suffix = [i.file_suffix for i in obj]
I tried many ways but no luck except the above but I know that's not the correct way. How can I get the file_suffix after creating the obj using file_id as filter?
Upvotes: 3
Views: 14905
Reputation: 328
You can do this as a one-liner with simply:
MainFile.objects.values_list('file_suffix', flat=True).get(file_id='e3e978a3-0375-4bb9-85a2-5175e2ec097d')
the values_list
queryset method retrieves only the column data that you need from the database. The get
method then returns the single match to your filter.
Upvotes: 7
Reputation: 13078
You can use get
instead of filter
obj = MainFile.objects.get(file_id='e3e978a3-0375-4bb9-85a2-5175e2ec097d')
obj.file_suffix
Use get
when your queryset will fetch at most 1 row back from the database. In this case, since file_id
is marked as the primary key, you can be certain that it is unique.
Upvotes: 7