updating multiple rows in django database - mysql

I have 5 records in the database and want to update all the values of a particular field called "ret_name".
For that, I have written the following code in views:
def retap_list(request, date_selected):
obj = ret_tbl.objects.filter(curr_date = date_selected)
obj[1].update(ret_name = "change")
print(obj[1].ret_name)
But it is showing me the following AttributeError:
"'ret_tbl' object has no attribute 'update'"
How should I update each row one at a time?

Actually, update method works on quesrysets not on the instances. So, you need to filter objects first and then:
objs = ret_tbl.objects.filter(curr_date=date_selected)
objs.update(ret_name="change")
All of the objects in queryset will be updated. If you need to update a particular object maybe it's a good idea to use save() instead.

Related

How to edit and save multiple records in database from spring boot

My problem is simple and straight forward. I want to edit multiple records and save them in database. For editing a single record, I have used following statement in JpaRepository
DatabaseEntity findByAbcId(Integer abcId);
Here, I am trying to fetch a record from Mysql database table DatabaseEntity with respect to its column named abcId which is a foreign key of another table named ABC.
In my service class, I get this record, set its attributes and simply save it back in database like:
//Getting an existing record from database:
//Giving hardcoded value just for understanding
DatabaseEntity databaseEntity = databaseEntityRepository.findByAbcId(106);
//Setting edited fields into Model object. Except for its own id and abcId(foreign key)
databaseEntity.setCol1(value);
databaseEntity.setCol2(value);
databaseEntity.setCol3(value);
databaseEntityRepository.save(databaseEntity);
The above code will get a record and save its edited version into the database.
Now lets take a similar scenario but this time, the database is retrieving multiple records. from the database. Suppose multiple records are present against abcId column in my table. The changes in my code will be:
//Storing the result in the list as there are multiple records stored against 106
List<DatabaseEntity> databaseEntity = databaseEntityRepository.findByAbcId(106);
//What should I code here?
Now I am confused how to set values in multiple fields in a single go from spring boot. The values that I need to edit are also in another list and I tried iterating over both lists and change the database records accordingly but my approach is not a good one
//List of those records which I have edited
if(newRecordsList != null) {
//Using atomic Integer because only that can be changed within lambda expression
AtomicInteger outerLoopCounter = new AtomicInteger(0);
List<DatabaseEntity> databaseEntity = databaseEntityRepository.findByAbcId(Abc.getId());
databaseEntity.forEach(obj -> {
AtomicInteger innerLoopCounter = new AtomicInteger(0);
newRecordsList.forEach(newRecordsListObj -> {
//condition so that first record is updated according to the updated first record and other changes are updated accordingly.
if(outerLoopCounter.get() == innerLoopCounter.get()) {
obj.setName(newRecordsListObj.getName());
obj.setCondition(newRecordsListObj.getCondition());
obj.setValue(newRecordsListObj.getValue());
databaseEntityRepository.save(obj);
}
innerLoopCounter.incrementAndGet();
});
outerLoopCounter.incrementAndGet();
});
}
I know this is a very bad approach and I want to update my logic. So please help me to update these multiple records inside database.
Thanks in advance

ActiveRecord: retrieve mySQL data based on one field in URL

I have a model called "blog", which has several columns, including one called "token".
I want to retrieve a row based on the token that's in a url - for instance, if the user goes to /blog/post1, I want to retrieve the row where token = post1
In my app setup I'm doing:
get '/blog/:id' do
#postID = params[:id]
#thePost = Blog.where(token: #postID)
render 'blog/index'
end
When I try to access <%= #thePost %> in my .erb file, I get:
#<Sequel::Mysql2::Dataset:0x007fdec1777318>
How do I access the actual data from the row here?
You are returning a relation, what you want to return is an actual record. To do this, use first at the end of your where call.
Blog.where(token: #postID).first
Blog.where(token: #postID) returns a list with all matches - even if the list contains only one elemen. OP is using the Sequel ORM instead of ActiveRecord (Hint is the return type Sequel::Mysql2::Dataset), therefore I would suggest to use first (or first! depending on your usecase) instead of where:
#thePost = Blog.first(token: #postID)
From the docs:
An alias for calling first on the model's dataset, but with optimized handling of the single argument case.

iterate over instance field containing multiple instances?

This is my fist time using django and I'm having some problems to understand how data is stored, so I can not really use it as I want to. I made many researches but I don't find any related question probably because I don't have the right keywords.
In my app model I created a WebPage and Count class:
class Count(models.Model):
date = models.DateField(default=date.today)
count = models.IntegerField(default=0)
class WebPage(models.Model):
link = models.CharField(max_length=60)
id = models.AutoField(primary_key=True)
clicks = models.IntegerField(default=0)
stats = models.ForeignKey(Count)
Then I created a WebPage object with multiple Count objects and I'd like to create a method to retrieve the sum of the count instances.
def get_clicks(self):
self.clicks=0
for object in self.stats:
self.clicks+=object.count
return str(self.clicks)
but I get the error 'Count' object is not iterable which is logic because I defined self.stats as an single Count object. I told my self that if the Count instances are not stored in self.stats they could be stored as "global" Count instances so I iterated over the object instances for object in self._meta.fields but the multiple Count instances are missing:
statistics.WebPage.link
statistics.WebPage.id
statistics.WebPage.clicks
statistics.WebPage.stats
And I think that iterate over the "global" Count objects it is not an option because I could not know which Count instance belong to which WebPage.
Where the self.stats Count instances hidden? Thanks for the help!
(I'm using django 1.7)
The problem is that your ForeignKey is the wrong way round. The model that the FK is defined in is the "many" side of the one-to-many relationship. That is, the way you have it, each Count has many WebPages, whereas I think you want the other way round.
Then you can sum the counts attached to your web page in one go via aggregation:
from django.db.models import Sum
total_clicks=my_web_page.count_set.aggregate(Sum('count'))
or, to get clicks for a whole queryset of webpages:
my_web_page_queryset.annotate(clicks=Sum('count__count'))
web_page = Webpage.objects.get(pk=1)
def get_clicks(web_page):
return web_page.contact_set.count()
This will work if you get a single Webpage. If you get a group of webpages, you can loop through them and call get_clicks for each.

How to get records with last dates in Django ORM(MySQL)?

I have models:
class Reference(models.Model):
name = models.CharField(max_length=50)
class Search(models.Model):
reference = models.ForeignKey(Reference)
update_time = models.DateTimeField(auto_now_add=True)
I have an instance of Reference and i need to get all last searches for the reference. Now i am doing it in this way:
record = Search.objects.filter(reference=reference)\
.aggregate(max_date=Max('update_time'))
if record:
update_time = record['max_date']
searches = reference.search_set.filter(update_time=self.update_time)
It is not a big deal to use 2 queries except the one but what if i need to get last searches for each reference on a page? I would have got 2x(count of references) queries and it would not be good.
I was trying to use this solution https://stackoverflow.com/a/9838438/293962 but it didn't work with filter by reference
You probably want to use the latest method.
From the docs, "Returns the latest object in the table, by date, using the field_name provided as the date field."
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#latest
so your query would be
Search.objects.filter(reference=reference).latest('update_time')
I implemented a snippet from someone in gist but I don't remember the user neither have the link.
A bit of context:
I have a model named Medicion that contains the register of mensuration of a machine, machines are created in a model instance of Equipo, Medicion instances have besides of a Foreign key to Equipo, a foreign key to Odometro, this model serves as a kind of clock or metre, that's why when I want to retrieve data (measurements aka instances of Medicion model) for a certain machine, I need to indicate the clock as well, otherwise it would retrieve me a lot of messy and unreadable data.
Here is my implementation:
First I retrieve the last dates:
ult_fechas_reg = Medicion.objects.values('odometro').annotate(max_fecha=Max('fecha')).order_by()
Then I instance an Q object:
mega_statement = Q() # This works as 'AND' Sql Statement
Then looping in every date retrieved in the queryset(annotation) and establishing the Q statement:
for r in ult_fechas_reg:
mega_statement |= (Q(odometro__exact=r['odometro']) & Q(fecha=r['max_fecha']))
Finally passed this mega statement to the queryset that pursues to retrieve the last record of a model filtered by two fields:
resultados = Medicion.objects.filter(mega_query).filter(
equipo=equipo,
odometro__in=lista_odometros).order_by('odometro', 'fecha') # lista_odometros is a python list containing pks of another model, don't worry about it.

How to access all the entries in MySQL table in Django View?

I am designing a Web Application using Django Framework. I have written the model code, urls.py and view code which can be seen Here.
I have added some data into the database table. But when I try to access the object using the code below, it just shows bookInfo objects five times. I don't think I am successful enough in pulling the data from the database. Kindly help.
View
def showbooks(request):
booklist = bookInfo.objects.order_by('Name')[:10]
output = ','.join([str(id) for id in booklist])
return HttpResponse(output)
You are iterating through the object list, you just need to reference the column/attribute you want:
output = ','.join([obj.id for obj in booklist])
Alternatively you can more more finely craft you original db call, then the iterable you use will work. In this case we'll pull out a list of the 'id' attribute.
booklist = bookInfo.objects.order_by('Name').values_list('id', flat=True)[:10]
output = ','.join([id for id in booklist])
I think you are successful in pulling the data. It is just that booklist contains objects, not numeric ids. You can add __unicode__ method to you class BookInfo that is supposed to return a string representation of the object (probably book name in this case). This method is going to be invoked when str() is applied. You can find more info about __unicode__ here.