简体   繁体   中英

How to use the created objects from get_or_create method?

Here if the object created I want to use this object in another model. How can I do it ? I suppose created returns the Boolean value so How can I get the created object ?

value, created = MyModel.objects.get_or_create(field1=field1, field2=field2)
if created:
     another_model_obj.manytomanyfield.add(created)

You should make use of the value , this is the object that is created:

value, created = MyModel.objects.get_or_create(field1=field1, field2=field2)
if created:
     another_model_obj.manytomanyfield.add()  # ← use value

The .get_or_create(…) [Django-doc] method returns a 2-tuple:

Returns a tuple of (object, created) , where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

So the first line " unpacks " the 2-tuple into two variables value and created where value is the object that is either obtained (if it already exists), or created (if it did not yet exists).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM