开发者

get_or_create() question

From the official documentation I can't understand what is default parameter.

obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
                  defaults={'birthday': date(1940, 10, 9)}

Does it mean that it will look for fields which match both John and Lennon parameter and birthday will just insert? Can I use something else instead of defaults?

And what method should I use to 开发者_如何学运维clean all fields in table (models)?

It give me FileField error can not resolve keyword default in field

So I need look for fiels, if i found it - update datas. If i didn't find it I have to crate new field... But, as I understud, It won't update me default fields when finde present fields.


It's quite obvious - if get_or_create finds queried object, the defaults keword does nothing. But if it creates object, then instance stored in obj has birthday field (in your example) filled with according value. You can pass any dictionary as defaults, as long as its keys are valid field names for model you're querying.

To clean the whole table, you should use something like:

Model.objects.all().delete()

which is equivalent of:

DELETE FROM app_model WHERE True;

To set some field in every object ( some column in every row ), there is update() method:

Model.objects.all().update( some_field = "" )

which translates to:

UPDATE app_model SET `some_field` = '' WHERE True;

My sql is a bit rusty, but I believe it goes like that, more or less.


You can refer to this django documentation for a more detailed explanation on get_or_create method. In short, it first tries to get with the first_name and last_name provided, if not it instantiates and saves a new object in which case the default dictionary is used. And the return value is the corresponding object and True/False whether a new object was created or not.


You can use anything. default if you not set anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜