Retrieve the matching object raising :class:`~mongoengine.queryset.MultipleObjectsReturned` or `DocumentName.MultipleObjectsReturned` exception if multiple results and :class:`~mongoengine.queryset.DoesNotExist` or `DocumentName.DoesNotExist` if no results are found.
(self, *q_objs, **query)
| 260 | return queryset |
| 261 | |
| 262 | def get(self, *q_objs, **query): |
| 263 | """Retrieve the matching object raising |
| 264 | :class:`~mongoengine.queryset.MultipleObjectsReturned` or |
| 265 | `DocumentName.MultipleObjectsReturned` exception if multiple results |
| 266 | and :class:`~mongoengine.queryset.DoesNotExist` or |
| 267 | `DocumentName.DoesNotExist` if no results are found. |
| 268 | """ |
| 269 | queryset = self.clone() |
| 270 | queryset = queryset.order_by().limit(2) |
| 271 | queryset = queryset.filter(*q_objs, **query) |
| 272 | |
| 273 | try: |
| 274 | result = next(queryset) |
| 275 | except StopIteration: |
| 276 | msg = "%s matching query does not exist." % queryset._document._class_name |
| 277 | raise queryset._document.DoesNotExist(msg) |
| 278 | |
| 279 | try: |
| 280 | # Check if there is another match |
| 281 | next(queryset) |
| 282 | except StopIteration: |
| 283 | return result |
| 284 | |
| 285 | # If we were able to retrieve the 2nd doc, raise the MultipleObjectsReturned exception. |
| 286 | raise queryset._document.MultipleObjectsReturned( |
| 287 | "2 or more items returned, instead of 1" |
| 288 | ) |
| 289 | |
| 290 | def create(self, **kwargs): |
| 291 | """Create new object. Returns the saved object instance.""" |
no test coverage detected