Actually, your User example is probably more like this: User.objects.get_or_create(name="Bob", age=40, defaults= {'admin'=True})
This tries to find a user by name and age, then uses a default value for the admin field, but does not look up or create the user by the admin field. On Feb 17, 9:08 am, Tim <timster...@gmail.com> wrote: > It's just as easy in Django. > > Tag.objects.get_or_create(name="Summer") > > User.objects.get_or_create(name="Bob", age=40, admin=True) > > On Feb 17, 8:33 am, Anders <anders.grimsrud.erik...@gmail.com> wrote: > > > Hi. > > > I do a lot of csv-import of data and have previously been using Ruby > > on Rails. And the only thing I miss about Rails (apart from database > > migration) is the find_or_create_by methods. > > > Are there any similar methods in Django? > > > My use is like this: > > > I import a CSV file, and in one column there is a value (i.e. a > > string). I don't want to store it as a string in Model1, but as a > > foreign key to Model2 - thus trying to find a record that has the > > string and returning the foreign key id if found - else create the > > object in Model2. > > > From the rails api: > > > # No 'Summer' tag exists > > Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => > > "Summer") > > > # Now the 'Summer' tag does exist > > Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name > > ("Summer") > > > # Now 'Bob' exist and is an 'admin' > > User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = > > true } > > > I know it's probably bad to say that Rails is good in some ways in a > > Django forum, so forgive me :) > > > Anders --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---