Django: How do I update only ONE record in my database? - sql

I'm having a lot of trouble trying to update a single (record) object in my database.
context['eval_list'] = Evaluering.objects.update(eval_relationer_id=self.kwargs.get('pk'))
I use objects.update, but it updates ALL my objects fk. How do I achieve only updating one object? I have also tried this:
context['eval_list'] = Evaluering.objects.update_or_create(eval_relationer_id=self.kwargs.get('pk'))
But this creates a new object and does not update the record that I want to update. I know why it creates a new objects, and it is because the FK I'm trying to update is null. Surely, there must be a way to only update and not create a single record? What am I missing here?
I tried adding a filter, but it feels redundant? I tried this:
context['eval_list'] = Evaluering.objects.filter(eval_relationer_id=self.kwargs.get('pk')).update(eval_relationer_id=self.kwargs.get('pk'))
I did consider trying to create an ID of the FK instantly and not later on, but I couldn't really get that to work, but if I created an ID then the update_or_create would work because an ID would exist already, BUT I cannot believe that I can't update a single object without create?
If creating the ID earlier on is the only work around, I will have to figure out how.

MyModel.objects.filter(pk=some_value).update(field1='some value')
The filter gets your object (returns the Queryset with only that object), then the update changes some other field that is not the PK to whatever you want.
In your case probably something like this:
context['eval_list'] = Evaluering.objects.filter(eval_relationer_id=self.kwargs.get('pk')).update(some_attribute='some value')

After help from #Hanny I've figured out was going wrong.
I was trying to filter by the eval_relationer_id, when I should have been filtering by the evaluation pk and getting that specific PK. Otherwise I would be updating ALL the values which is not what I wanted.
So by filtering by pk:
filter(pk=self.kwargs.get('pk'))
And updating by the attribute / fk that I want to update
update(eval_relationer_id=self.kwargs.get('pk'))
This is the end-result:
context['eval_list'] = Evaluering.objects.filter(pk=self.kwargs.get('pk')).update(eval_relationer_id=self.kwargs.get('pk'))

Related

Remove object from Active Record Relation without deleting it

I'm working in Ruby on Rails 4 with Postgresql, and I've hit a bit of a snag. We have an Active Record model called AttendanceRecord which belongs to an AttendanceDay, AttendanceSwipe, Course, and CourseTimeSlot. Attendance Records were supposed to be unique on these fields, but something went wrong and duplicates snuck in. So, I wrote a method to find all of the Attendance Records which were duplicated and only keep one of them.
In the course of that method, I built an Active Record Relation of objects that shared the same attributes, like so:
records = AttendanceRecord.where(course_id: attributes[0], course_time_slot_id: attributes[1], attendance_swipe_id: attributes[2], attendance_day_id: attributes[3])
Nice relation, right?
Next, I found the object that I wanted to keep and named it to_keep. Then, I tried to remove just that object from the relation, like this:
records.delete(to_keep)
Unfortunately, I discovered that the delete method works a little differently on a Relation than it does on an Array. Instead of simply removing the object from the list, it actually does delete it from the database (without the callbacks).
So: I'm wondering if there is a method that I'm missing that will remove my to_keep object from the Relation without actually touching the object itself. Then, I'll be able to safely call records.destroy_all and happily go about my business. :)
If you want to exclude an object from a relation you can do so by id. For example:
records.where('id <> ?', to_keep.id).destroy_all
or, thanks to #trushkevich, in rails 4 you can do:
records.where.not(id: to_keep.id).destroy_all
This means that destroy_all will be called on the records you've identified already but excluding the to_keep record.

SQL UPDate same table

I know this has been posted before but I am not sure I have got my head around the logic let aloan trying to get it into to JET Friendly Syntax.
Here is what I am trying to do
I have a bunch of records that relate to documents and I am planning on renaming the documents with GUID's however some records point to the same document here lays the problem.
Table
ID, LegacyFullPathNme, GUID, isDuplicate
my code loops through and assigns each record a GUID. then I want to update the Duplicate Documents records with the same GUID
below is my hash at it but doesn't work "Operation must use an updateable Query
UPDATE [IO Documents] a
set a.codedFileName = (SELECT B.codedFileName
FROM [IO Documents] b
WHERE b.LegacyFullPathName = a.LegacyFullPathName)
Currently use a macro to go throw RBAR
I'm a little confused on why you would do it this way since now your globally unique id column isn't unique in that multiple rows will have it.
I think a better method would be to simply create a new table from your old one with a row for each file path.
SELECT LegacyFullPathNme
INTO newtable
FROM oldtable
GROUP BY LegacyFullPathNme;
and then add the guid into the new table afterwards. (note that I didn't test that sql snippet so that might not be proper syntax but I think it gets the point across).
I believe you are looking for something like this:
UPDATE [IO Documents] SET
codedFileName = DMin("codedFileName","IO Documents","LegacyFullPathName='" & LegacyFullPathName & "'")

How do I get NHibernate to save an entity if I assign it an ID, but generate one otherwise?

According to the REST philosophy, a PUT request should update the resource at a URL if it exists, and create it if it doesn't exist. So in other words, if I use the following URL:
PUT http://server/item/5
If an Item exists with an ID of 5, it will be updated. If an Item doesn't exist with an ID of 5, a new Item will be created with an ID of 5.
However, I'm using NHibernate for persistence, and I mapped my IDs as Identity. This means that no matter what value I assign the ID, NHibernate will replace it with its own when I save a new Item.
How do I get NHibernate to save an Item with the ID that I assign it, without changing the ID mapping to Assigned?
If you use Identity, the DB won't allow you to enter a value.
That said, if your DB has some special syntax to allow inserting with explicit values in Identity fields, you can implement your own generator, which I guarantee will be error prone, hard to debug, and not very useful. But it's possible.
Study everything in https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Id and start creating your Frankenstein :-)

Table not getting updated while using LinQ

I am trying to update a table using LinQ. Though records are getting inserted, for some reason they are not getting updated.
what can be possible problem
Dim db as new empDataContext
Dim emptable as new employee
if update then
emptable=GetEmp(txtempID.Text)
emptable.Name="Test"
emptable.Age=11
emptable.City="NYC"
else
emptable.Name="Test"
emptable.Age=11
emptable.City="NYC"
emtable.deptID=10
db.employee.InsertOnSubmit(emptable)
end if
db.SubmitChanges()
Judging just from what I can see here, I'm guessing your GetEmp method is using a different data context to retreive the data than the one you're using to save it back to the DB.
When using LINQ to SQL, the context is what tracks the changes to the tables. If you're not careful and mix Contexts by accident, you can get strange behaviors like this.
You can test by chaging:
emptable=GetEmp(txtempID.Text)
to
// Returns the first matching employee with the id
emptable = (from e in db.Employees
where e.id == txtempid.Text).FirstOrDefault()
If you find that the context is the issue, just modify your GetEmp method to accept the context as a parameter rather than creating a new one itself.
What does GetEmp do? In particular, as presented it appears that it does not have a reference to the empDataContext named db. DataContexts are examples of identity maps and as such they track items that have been loaded from a persistence mechanism. If you are using a different DataContext in GetEmp then the DataContext db does not know about the instance of employee with SomeID equal to the value represented by txtempID.Text.
So either pass a reference to db into GetEmp or change your code to the following:
emptable = db.Single(Function(e as employee) e.SomeID=Int32.Parse(txtempID.Text))
then your update should work.
If I had to guess, I would say that the GetEmp() call is not using the same database context object. Therefore, Linq-To-SQL doesn't think any changes are occuring in the "db" database context.
Randy

In a datacontext are inserted values not available within the datacontext until after submitchanges?

I'm going through an XML file of articles and the journalist(s) that wrote them. As we are adding the articles into _Data our datacontext we may come across a journalist that needs adding so we do this:
newJourno = New journalist With {.name = strJournalist}
_Data.journalists.InsertOnSubmit(newJourno)
.articles_journalists.Add(New articles_journalist With {.id_journalist = newJourno.id, .id_article = .id})
However subsequently we may come across this same journalist again and nothing is returned when we do this:
Dim journo = _Data.journalists.Where(Function(s) s.name = strJournalist).SingleOrDefault
So it uses the code above again to insert the same journalist again.
Once all of our inserts are done we do a submitchanges. At this point it has a head fit:
INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_articles_journalists_journalists'. The conflict occurred in database 'blah', table 'journalists', column 'id'. The statement has been terminated.
From looking through the sql generated in sql profiler you can see that it is trying to add some journalists more than once, this will fail as the name must be distinct. The subsequent records that are trying to be inserted with these journalists are failing as the journalist wasn't updated.
Surely if I have a collection of journalists, add some to it and then look in my collection I should see all of them and not just the original ones. I can fudge it I guess by doing a submitchanges but that seems a bit silly.
Thanks in advance,
Dave.
If you want to add two child-parent rows to the database, you must assign the entity, instead of the Id column, the Id will be autogenerated and will be available only after the submit changes.
You have to do a articles_journalist object, and then assign the newJourno entity to this:
articles_journalist.journalist = newJourno;
CMS is right about needing to assign the object, not the id.
However this doesn't seem to get around the problem of the datacontext not realising that it has had new stuff added to it until you submitchanges. I can only presume this is by design and therefore I am now calling submitchanges as and when the code inserts objects that we later search for.
"the name must be distinct."
This is a serious design flaw. Person names are never unique.