Search code examples
pythonpython-3.xdjangodjango-modelsexport-to-csv

how to fetch name in instead of id in django


I have a ServiceProvider model. When I import it in CSV it provider ID of category, country, state, city, name. How I fetch the name instead of ID while import in CSV.

Here is my models.py

class ServiceProvider(models.Model):
    name = models.OneToOneField('accounts.User', on_delete=models.CASCADE)
    Date_Of_Birth = models.DateField(null=True)
    # upload_Photograph = models.ImageField(upload_to='images/') 
    Education_Qualification  = models.CharField(max_length=254, null=True)
    category = models.ForeignKey('accounts.Category', null=True, on_delete=models.CASCADE, related_name='category')
    phone_No = models.IntegerField(null=False)
    alternate_No = models.IntegerField(null=True)
    bank_account_no = models.IntegerField(null=True)
    IFSC_code = models.IntegerField(null=True)
    branch_name = models.CharField(max_length=254, null=True)
    PAN = models.CharField(max_length=254, null=True)
    country = models.ForeignKey('accounts.Country', null=True, on_delete=models.CASCADE, related_name='country')
    state = models.ForeignKey('accounts.State', null=True, on_delete=models.CASCADE, related_name='state')
    cities = models.ForeignKey('accounts.City', null=True, on_delete=models.CASCADE, related_name='cities')
    address = models.CharField(max_length=254)


    def __str__(self):
        return self.name.username

Here is my views.py

@login_required
def export_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="user-serviceprovider.xls"'
    writer = csv.writer(response)
    writer.writerow(['name', 'Date_Of_Birth', 'Education_Qualification', 'category','phone_No','alternate_No','bank_account_no','IFSC_code','branch_name','PAN','country','state','cities','address'])
    users = ServiceProvider.objects.all().values_list('name', 'Date_Of_Birth', 'Education_Qualification', 'category','phone_No','alternate_No','bank_account_no','IFSC_code','branch_name','PAN','country','state','cities','address')
    for user in users:
      writer.writerow(user)     
    return response

Solution

  • I think what you really is need is a little tweak like this:

    ...
    users = ServiceProvider.objects.all().values_list('name__username', 'Date_Of_Birth', 'Education_Qualification', 'category','phone_No','alternate_No','bank_account_no','IFSC_code','branch_name','PAN','country','state','cities','address')
    ...
    

    Notice that 'name__username', it tells Django to go a bit deeper and select the username column from the accounts.User table because plain 'name' refers to the foreign key in the ServiceProvider table (here username is just an example, the actual name of the column really depends on the schema of your accounts.User table).