<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def upsert( queryset, model_objs, unique_fields, update_fields=None, returning=False, sync=False, ignore_duplicate_updates=True, return_untouched=False ):
 """ Perform a bulk upsert on a table, optionally syncing the results. Args: queryset (Model|QuerySet):
 A model or a queryset that defines the collection to sync model_objs (List[Model]):
 A list of Django models to sync. All models in this list will be bulk upserted and any models not in the table (or queryset) will be deleted if sync=True. unique_fields (List[str]):
 A list of fields that define the uniqueness of the model. The model must have a unique constraint on these fields update_fields (List[str], default=None):
 A list of fields to update whenever objects already exist. If an empty list is provided, it is equivalent to doing a bulk insert on the objects that don't exist. If `None`, all fields will be updated. returning (bool|List[str]):
 If True, returns all fields. If a list, only returns fields in the list sync (bool, default=False):
 Perform a sync operation on the queryset ignore_duplicate_updates (bool, default=False):
 Don't perform an update if the row is a duplicate. return_untouched (bool, default=False):
 Return untouched rows by the operation """

    queryset = queryset if isinstance(queryset, models.QuerySet) else queryset.objects.all()
    model = queryset.model

    # Populate automatically generated fields in the rows like date times
    _fill_auto_fields(model, model_objs)

    # Sort the rows to reduce the chances of deadlock during concurrent upserts
    model_objs = _sort_by_unique_fields(model, model_objs, unique_fields)
    update_fields = _get_update_fields(model, unique_fields, update_fields)

    return _fetch(queryset, model_objs, unique_fields, update_fields, returning, sync,
                  ignore_duplicate_updates=ignore_duplicate_updates,
                  return_untouched=return_untouched)