Reputation: 39
I need to do some math against a value and I'm very confused about F(). I've read through the docs and searched for examples but I'm missing some fundamentals. Could you help with a solution and give some pointers about how to make sense of this? My attempts below are commented out. I'm just trying to convert Mb to GB. If I could get a 2 decimal value that would be be really wonderful.
class DatastoreInfo(models.Model):
[ ... ]
total_capacity = models.IntegerField(db_column='Total_Capacity', blank=True, null=True)
[ ... ]
class Meta:
managed = False
db_table = 'Datastore_Info'
def ecsdatastores(request):
form = myForm()
results = {}
if request.method == 'POST':
if 'listxyz' in request.POST:
form = myForm(request.POST)
taf = form['taf'].value()
results = DatastoreInfo.objects.filter(f_hostname=c_name)
# results = DatastoreInfo.objects.filter(f_hostname=c_name, total_capacity=F('total_capacity') / 1000)
# results = DatastoreInfo.objects.update(total_capacity=F('total_capacity') / 1000).filter(f_hostname=c_name)
return render(request, 'dpre/datastoreinfo.html', {'form': form , 'results': results})
Upvotes: 0
Views: 467
Reputation: 359
You almost are there. You need to organize your query so first you filter down to the applicable rows, and then you apply the update with the F function as the value.
# First take your filtered rows
results = DatastoreInfo.objects.filter(f_hostname=c_name)
# Then, on the filtered queryset, you can apply the update.
results.update(total_capacity=F('total_capacity') / 1000)
You can see this is just like the reporter example from the Django F Expression Documentation.
reporter = Reporters.objects.filter(name='Tintin')
reporter.update(stories_filed=F('stories_filed') + 1)
Edit: As a side note you may want to divide by 1024, not 1000, if converting from GB to MB.
Upvotes: 1