def _check_fields(self, cls, model): """ Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if cls.fields is None: return [] elif not isinstance(cls.fields, (list, tuple)): return must_be('a list or tuple', option='fields', obj=cls, id='admin.E004') elif cls.fieldsets: return [ checks.Error( 'Both "fieldsets" and "fields" are specified.', hint=None, obj=cls, id='admin.E005', ) ] fields = flatten(cls.fields) if len(fields) != len(set(fields)): return [ checks.Error( 'There are duplicate field(s) in "fields".', hint=None, obj=cls, id='admin.E006', ) ] return list(chain(*[ self._check_field_spec(cls, model, field_name, 'fields') for field_name in cls.fields ]))
def test_flatten(self): flat_all = ['url', 'title', 'content', 'sites'] inputs = (((), []), (('url', 'title', ('content', 'sites')), flat_all), (('url', 'title', 'content', 'sites'), flat_all), ((('url', 'title'), ('content', 'sites')), flat_all)) for orig, expected in inputs: self.assertEqual(flatten(orig), expected)
def _check_fieldsets_item(self, cls, model, fieldset, label): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be('a list or tuple', option=label, obj=cls, id='admin.E008') elif len(fieldset) != 2: return must_be('of length 2', option=label, obj=cls, id='admin.E009') elif not isinstance(fieldset[1], dict): return must_be('a dictionary', option='%s[1]' % label, obj=cls, id='admin.E010') elif 'fields' not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, hint=None, obj=cls, id='admin.E011', ) ] fields = flatten(fieldset[1]['fields']) if len(fields) != len(set(fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, hint=None, obj=cls, id='admin.E012', ) ] return list(chain(*[ self._check_field_spec(cls, model, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]['fields'] ]))
def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E008') elif len(fieldset) != 2: return must_be('of length 2', option=label, obj=obj, id='admin.E009') elif not isinstance(fieldset[1], dict): return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010') elif 'fields' not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id='admin.E011', ) ] elif not isinstance(fieldset[1]['fields'], (list, tuple)): return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, id='admin.E008') seen_fields.extend(flatten(fieldset[1]['fields'])) if len(seen_fields) != len(set(seen_fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id='admin.E012', ) ] return list(chain.from_iterable( self._check_field_spec(obj, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]['fields'] ))
def _check_fieldsets_item(self, obj, model, fieldset, label): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be("a list or tuple", option=label, obj=obj, id="admin.E008") elif len(fieldset) != 2: return must_be("of length 2", option=label, obj=obj, id="admin.E009") elif not isinstance(fieldset[1], dict): return must_be("a dictionary", option="%s[1]" % label, obj=obj, id="admin.E010") elif "fields" not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id="admin.E011" ) ] elif not isinstance(fieldset[1]["fields"], (list, tuple)): return must_be("a list or tuple", option="%s[1]['fields']" % label, obj=obj, id="admin.E008") fields = flatten(fieldset[1]["fields"]) if len(fields) != len(set(fields)): return [ checks.Error("There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id="admin.E012") ] return list( chain( *[ self._check_field_spec(obj, model, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]["fields"] ] ) )
def _check_fields(self, obj): """ Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if obj.fields is None: return [] elif not isinstance(obj.fields, (list, tuple)): return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004') elif obj.fieldsets: return [ checks.Error( "Both 'fieldsets' and 'fields' are specified.", hint=None, obj=obj.__class__, id='admin.E005', ) ] fields = flatten(obj.fields) if len(fields) != len(set(fields)): return [ checks.Error( "The value of 'fields' contains duplicate field(s).", hint=None, obj=obj.__class__, id='admin.E006', ) ] return list(chain(*[ self._check_field_spec(obj, obj.model, field_name, 'fields') for field_name in obj.fields ]))
def test_flatten(self): flat_all = ["url", "title", "content", "sites"] inputs = ( ((), []), (("url", "title", ("content", "sites")), flat_all), (("url", "title", "content", "sites"), flat_all), ((("url", "title"), ("content", "sites")), flat_all), ) for orig, expected in inputs: self.assertEqual(flatten(orig), expected)
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() all_users = user_models.User.objects.all() room_types = room_models.RoomType.objects.all() seeder.add_entity( room_models.Room, number, { "name": lambda x: seeder.faker.address(), "host": lambda x: random.choice(all_users), "room_type": lambda x: random.choice(room_types), "guests": lambda x: random.randint(1, 20), "price": lambda x: random.randint(1, 300), "beds": lambda x: random.randint(1, 5), "bedrooms": lambda x: random.randint(1, 5), "baths": lambda x: random.randint(1, 5), }, ) created_photos = seeder.execute() created_clean = flatten(list(created_photos.values())) amenities = room_models.Amenity.objects.all() facilities = room_models.Facility.objects.all() rules = room_models.HouseRule.objects.all() for pk in created_clean: room = room_models.Room.objects.get(pk=pk) for i in range(3, random.randint(10, 30)): room_models.Photo.objects.create( caption=seeder.faker.sentence(), room=room, file=f"room_photos/{random.randint(1, 31)}.webp", ) for a in amenities: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room.amenities.add(a) for f in facilities: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room.facilities.add(f) for r in rules: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room.house_rules.add(r) self.stdout.write(self.style.SUCCESS(f"{number} rooms created!"))
def handle(self, *args, **options): hosts = User.objects.all() room_type = RoomType.objects.all() number = options.get("number") seeder = Seed.seeder() seeder.add_entity( Room, number, { "name": lambda x: seeder.faker.address(), "host": lambda x: random.choice(hosts), "room_type": lambda x: random.choice(room_type), "guests": lambda x: random.randint(1, 5), "price": lambda x: random.randint(25000, 50000), "beds": lambda x: random.randint(1, 5), "baths": lambda x: random.randint(1, 5), "bedrooms": lambda x: random.randint(1, 5), }, ) clean_room = seeder.execute() clean_room_pk = flatten(list(clean_room.values())) amenities = Amenity.objects.all() facilities = Facility.objects.all() rules = HouseRule.objects.all() for pk in clean_room_pk: room_pk = Room.objects.get(pk=pk) for i in range(3, random.randint(12, 30)): Photo.objects.create( caption=seeder.faker.sentence(), room=room_pk, file=f"/room_photos/{random.randint(1, 15)}.jpeg", ) for a in amenities: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room_pk.amenities.add(a) for f in facilities: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room_pk.facilities.add(f) for r in rules: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room_pk.house_rules.add(r) self.stdout.write(self.style.SUCCESS(f"{number} Room Created!"))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() users = user_models.User.objects.all() rooms = room_models.Room.objects.all() seeder.add_entity( list_models.List, number, {"user": lambda x: random.choice(users),}, ) created = seeder.execute() cleaned = flatten(list(created.values())) for pk in cleaned: list_model = list_models.List.objects.get(pk=pk) to_add = rooms[random.randint(0, 5) : random.randint(6, 30)] list_model.rooms.add(*to_add) self.stdout.write(self.style.SUCCESS(f"{number} {NAME} created!"))
def handle(self, *args, **options): number = int(options.get("number", 1)) rooms = room_models.Room.objects.all() users = user_models.User.objects.all() seeder = Seed.seeder() seeder.add_entity(list_models.List, number, {"user": lambda x: random.choice(users)}) created_lists = seeder.execute() clean_lists = flatten(list(created_lists.values())) for pk in clean_lists: list_model = list_models.List.objects.get(pk=pk) to_add = rooms[random.randint(0, 5):random.randint(6, 30)] list_model.rooms.add(*to_add) self.stdout.write(self.CRED + "List 생성!" + self.CEND)
def _check_fields(self, cls, model): """ Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ if cls.fields is None: return [] elif not isinstance(cls.fields, (list, tuple)): return must_be("a list or tuple", option="fields", obj=cls, id="admin.E004") elif cls.fieldsets: return [checks.Error("Both 'fieldsets' and 'fields' are specified.", hint=None, obj=cls, id="admin.E005")] fields = flatten(cls.fields) if len(fields) != len(set(fields)): return [ checks.Error("The value of 'fields' contains duplicate field(s).", hint=None, obj=cls, id="admin.E006") ] return list(chain(*[self._check_field_spec(cls, model, field_name, "fields") for field_name in cls.fields]))
def test_same_entries_in_same_vertical_order(entries_27, settings_NUMBER_OF_COLUMNS_4): # All the entries received are still there and are vertically sorted in the same order as received # Note entries_27 spread over 4 rows means 7 rows with the last row having 1 null entry in the last position # Null entries must be removed. They were just filler to complete the row and keep the template happy. instance = EvenVMCView() rows = instance.process_entries(entries_27) temp_list = [] for c in range(4): temp_list.append([ rows[r][c]["name"] if rows[r][c] != "" else "to-be-removed" for r in range(7) ]) temp_list = flatten(temp_list) generated_entries = [e for e in temp_list if e != "to-be-removed"] original_entries = [e["name"] for e in entries_27] assert original_entries == generated_entries
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() all_users = user_models.User.objects.all() room_types = room_models.RoomType.objects.all() seeder.add_entity( room_models.Room, number, { 'name': lambda x: seeder.faker.address(), 'host': lambda x: random.choice(all_users), 'room_type': lambda x: random.choice(room_types), 'guests': lambda x: random.randint(0, 20), 'price': lambda x: random.randint(0, 300), 'beds': lambda x: random.randint(0, 5), 'bedrooms': lambda x: random.randint(0, 5), 'baths': lambda x: random.randint(0, 5), }) created_photos = seeder.execute() created_clean = flatten(list(created_photos.values())) amenities = room_models.Amenity.objects.all() facilities = room_models.Facility.objects.all() house_rules = room_models.HouseRule.objects.all() for pk in created_clean: room = room_models.Room.objects.get(pk=pk) for i in range(3, random.randint(10, 30)): room_models.Photo.objects.create( caption=seeder.faker.sentence(), file=f"room_photos/{random.randint(1,31)}.webp", room=room, ) # Add something in manyTomany relationship for a in amenities: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room.amenities.add(a) for f in facilities: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room.facilities.add(f) for h in house_rules: magic_number = random.randint(0, 15) if magic_number % 2 == 0: room.house_rules.add(h) self.stdout.write(self.style.SUCCESS(f"{number} rooms created!!"))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() seeder.add_entity( team_models.Team, number, { "name": lambda x: seeder.faker.user_name(), "active_region": lambda x: seeder.faker.address(), "is_solo": lambda x: random.choice([True, False]), }, ) created_teams = seeder.execute() created_teams = flatten(list(created_teams.values())) for team in created_teams: team = team_models.Team.objects.get(pk=team) added_users = user_models.User.objects.order_by( "?").all()[:random.randint(1, 5)] users_positions = [] users_genres = [] for user in added_users: users_positions += user.positions.all() users_genres += user.genres.all() users_positions = set(users_positions) users_genres = set(users_genres) # Give users, positions and genres to Team for user in added_users: team.users.add(user) for position in users_positions: team.positions.add(position) for genre in users_genres: team.genres.add(genre) team.save() self.stdout.write(self.style.SUCCESS(f"{number} teams created!"))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() room_types = room_models.RoomType.objects.all() all_users = User.objects.all() seeder.add_entity( room_models.Room, number, { "name": lambda x: seeder.faker.address(), "room_type": lambda x: random.choice(room_types), "host": lambda x: random.choice(all_users), "beds": lambda x: random.randint(1, 5), "baths": lambda x: random.randint(1, 5), "bedrooms": lambda x: random.randint(1, 5), "guests": lambda x: random.randint(1, 5), }, ) amenities = room_models.Amenity.objects.all() facilities = room_models.Facility.objects.all() house_rules = room_models.HouseRule.objects.all() created_photos = seeder.execute() room_id = flatten(list(created_photos.values())) for pk in room_id: room = room_models.Room.objects.get(pk=pk) for photo in range(3, random.randint(10, 30)): room_models.Photo.objects.create( caption=seeder.faker.sentence(), room=room, file=f"/room_photos/{random.randint(1,19)}.webp", ) for amenity in amenities: random_num = random.randint(0, 15) if random_num % 3 == 0: room.amenities.add(amenity) for facility in facilities: random_num = random.randint(0, 15) if random_num % 2 == 0: room.facilities.add(facility) for rule in house_rules: random_num = random.randint(0, 15) if random_num % 3 == 0: room.house_rules.add(rule) self.stdout.write(self.style.SUCCESS(f"{number} rooms have been created!"))
def handle(self, *args, **options): number = int(options.get("number")) all_users = User.objects.all() all_room_types = room_models.RoomType.objects.all() amenities = room_models.Amenity.objects.all() facilities = room_models.Facility.objects.all() rules = room_models.HouseRule.objects.all() seeder.add_entity( room_models.Room, number, { "name": lambda x: seeder.faker.street_name(), "host": lambda x: random.choice(all_users), "room_type": lambda x: random.choice(all_room_types), "price": lambda x: random.randint(10000, 500000), "beds": lambda x: random.randint(0, 10), "bedrooms": lambda x: random.randint(0, 10), "baths": lambda x: random.randint(0, 10), "guests": lambda x: random.randint(1, 20), "city": lambda x: seeder.faker.city(), "country": lambda x: seeder.faker.country(), }, ) # photo created = seeder.execute() created_clean = flatten(list(created.values())) for pk in created_clean: room = room_models.Room.objects.get(pk=pk) for i in range(1, random.randint(3, 5)): room_models.Photo.objects.create( caption=seeder.faker.sentence(), file=f"/rooms/photos_seed/{random.randint(1,31)}.webp", room=room, ) add_random(room.amenity, amenities) add_random(room.facility, facilities) add_random(room.house_rules, rules) self.stdout.write(self.style.SUCCESS(f"{number} rooms created!"))
def handle(self, *args, **options): number = options.get('number', 1) seeder = Seed.seeder() all_users = User.objects.all() all_roomtypes = RoomType.objects.all() seeder.add_entity( Room, number, { 'name': lambda x: seeder.faker.address(), 'host': lambda x: random.choice(all_users), 'room_type': lambda x: random.choice(all_roomtypes), 'price': lambda x: 100 * random.randint(100, 1000), 'guests': lambda x: random.randint(1, 5), 'bedrooms': lambda x: random.randint(1, 5), 'beds': lambda x: random.randint(1, 5), 'baths': lambda x: random.randint(1, 5) }) created_photos = seeder.execute() created_clean = flatten(list(created_photos.values())) amenities = room_models.Amenity.objects.all() facilities = room_models.Facility.objects.all() rules = room_models.HouseRule.objects.all() for pk in created_clean: room = room_models.Room.objects.get(pk=pk) for i in range(3, random.randint(5, 7)): room_models.Photo.objects.create( caption=seeder.faker.sentence(), room=room, file=f'/room_photos/{random.randint(1,31)}.webp') for a in amenities: magic_number = random.randint(1, 15) if magic_number % 2 == 0: room.amenity.add(a) for a in facilities: magic_number = random.randint(1, 15) if magic_number % 2 == 0: room.facility.add(a) for a in rules: magic_number = random.randint(1, 15) if magic_number % 2 == 0: room.house_rule.add(a) self.stdout.write( self.style.SUCCESS(f'{number} Room has been created'))
def handle(self, *args, **options): times = options.get('times') seeder = Seed.seeder() seeder.add_entity( Room, times, { 'title': lambda x: random.choice(titles), 'description': lambda x: seeder.faker.text(), 'host': lambda x: random.choice(all_users), }) created_rooms = seeder.execute() created_clean = flatten(list(created_rooms.values())) for pk in created_clean: room = Room.objects.get(pk=pk) for i in range(3, random.randint(5, 10)): RoomPhoto.objects.create( file=f'rooms/{random.choice(room_photo_filenames)}', caption=seeder.faker.sentence(), room=room)
def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be("a list or tuple", option=label, obj=obj, id="admin.E008") elif len(fieldset) != 2: return must_be("of length 2", option=label, obj=obj, id="admin.E009") elif not isinstance(fieldset[1], dict): return must_be( "a dictionary", option="%s[1]" % label, obj=obj, id="admin.E010" ) elif "fields" not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, obj=obj.__class__, id="admin.E011", ) ] elif not isinstance(fieldset[1]["fields"], (list, tuple)): return must_be( "a list or tuple", option="%s[1]['fields']" % label, obj=obj, id="admin.E008", ) seen_fields.extend(flatten(fieldset[1]["fields"])) if len(seen_fields) != len(set(seen_fields)): return [ checks.Error( "There are duplicate field(s) in '%s[1]'." % label, obj=obj.__class__, id="admin.E012", ) ] return list( chain.from_iterable( self._check_field_spec(obj, fieldset_fields, '%s[1]["fields"]' % label) for fieldset_fields in fieldset[1]["fields"] ) )
def generate_options_for_backup_plan(**kwargs): backup_plan_ids = [] env = Environment.objects.filter( resource_handler__resource_technology__name="Amazon Web Services" ).first() rh = env.resource_handler.cast() for region in get_all_regions(): client = boto3.client('backup', region_name=region, aws_access_key_id=rh.serviceaccount, aws_secret_access_key=rh.servicepasswd) backup_plan_ids.append([ (backup_plan_id.get('BackupPlanId') + ',' + backup_plan_id.get('BackupPlanName'), backup_plan_id.get('BackupPlanName')) for backup_plan_id in client.list_backup_plans().get( 'BackupPlansList') ]) return flatten(backup_plan_ids)
def handle(self, *args, **options): # print(args, options) # get number from console number = options.get("number") seeder = Seed.seeder() # importing foreignkey field at models.py all_users = user_models.User.objects.all() all_rooms = room_models.Room.objects.all() print(all_users) # https://docs.djangoproject.com/en/3.0/ref/models/querysets/#when-querysets-are-evaluated # users_list = list(all_users) # print(users_list) # add entities to seeder packet seeder.add_entity( list_models.List, number, # foreignkey field wrapped as queryset {"user": lambda x: random.choice(all_users)}, ) # inject seeder packet to the databse # executing seeder created = seeder.execute() # allocating random rooms to list cleaned = flatten(list(created.values())) for pk in cleaned: # getting list class item with primary key list_model = list_models.List.objects.get(pk=pk) # list of rooms from random number to random number random_int1 = random.randint(0, 5) random_int2 = random.randint(6, 30) to_add = all_rooms[random_int1:random_int2] # below is "rooms" field at lists.models class List list_model.rooms.add(*to_add) # stand out self.stdout.write(self.style.SUCCESS(f"{number} {NAME} created"))
def get_readonly_fields(self, request, obj=None): """ Return all fields as readonly for the view permission """ # get read_only fields specified on the admin class is available # (needed for @property fields) readonly_fields = super(AdminViewPermissionBaseModelAdmin, self).get_readonly_fields(request, obj) if ((self.has_view_permission(request, obj) and ( obj and not self._has_change_only_permission(request, obj))) or ( obj is None and not self.has_add_permission(request))): if self.fields: # Set as readonly fields the specified fields readonly_fields = flatten(self.fields) else: readonly_fields = ( list(readonly_fields) + [field.name for field in self.opts.fields if field.editable] + [field.name for field in self.opts.many_to_many if field.editable] ) # remove duplicates whilst preserving order readonly_fields = list(OrderedDict.fromkeys(readonly_fields)) # Try to remove id if user has not specified fields and # readonly fields try: readonly_fields.remove('id') except ValueError: pass # Remove from the readonly_fields list the excluded fields # specified on the form or the modeladmin excluded_fields = self.get_excluded_fields() if excluded_fields: readonly_fields = [ f for f in readonly_fields if f not in excluded_fields ] return tuple(readonly_fields)
def handle(self, *args, **options): number = options.get('number') seeder = Seed.seeder() all_user = user_model.User.objects.all() room_types = room_model.RoomType.objects.all() seeder.add_entity( room_model.Room, number, { 'name': lambda x: seeder.faker.address(), 'host': lambda x: random.choice(all_user), 'room_type': lambda x: random.choice(room_types), "guests": lambda x: random.randint(0, 20), 'price': lambda x: random.randint(0, 300), 'beds': lambda x: random.randint(0, 5), 'bedrooms': lambda x: random.randint(0, 5), 'baths': lambda x: random.randint(0, 5), }) created_photos = seeder.execute() created_clean = flatten(list(created_photos.values())) amenities = room_model.Amenity.objects.all() facilities = room_model.Facility.objects.all() for pk in created_clean: room = room_model.Room.objects.get(pk=pk) for i in range(3, random.randint(10, 30)): room_model.Photo.objects.create( caption=seeder.faker.sentence(), room=room, file=f"/media/{random.randint(1,31)}.webp", ) for a in amenities: num = random.randint(0, 15) if num % 2 == 0: room.amenities.add(a) for a in facilities: num = random.randint(0, 15) if num % 2 == 0: room.facilities.add(a) self.stdout.write(self.style.SUCCESS("Rooms created!"))
def handle(self, *args, **options): number = options.get("number", 1) users = user_models.User.objects.all() seeder = Seed.seeder() seeder.add_entity( conversation_models.Conversation, number, ) conversations_pk = seeder.execute() conversations_pk = flatten(conversations_pk.values()) for conversation_pk in conversations_pk: conversation_model = conversation_models.Conversation.objects.get( pk=conversation_pk) add_users = users[randint(0, 5):randint(5, 10)] conversation_model.participants.add(*add_users) self.stdout.write(self.style.SUCCESS(f"Create {number} {NAME}"))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() users = user_models.User.objects.all() rooms = room_models.Room.objects.all() seeder.add_entity(list_models.List, number, { "user": lambda x: random.choice(users), }) created = seeder.execute() cleaned = flatten(list(created.values())) for pk in cleaned: list_model = list_models.List.objects.get(pk=pk) to_add = rooms[random.randint(0, 5):random.randint(6, 30)] # this will be a querset and I want elements inside of the queryset list_model.rooms.add(*to_add) self.stdout.write( self.style.SUCCESS(f"{NAME} are created successfully!"))
def get_fields(self, request, obj=None): """ If the user has only the view permission return these readonly fields which are in fields attr """ if ((self.has_view_permission(request, obj) and (obj and not self._has_change_only_permission(request, obj))) or (obj is None and not self.has_add_permission(request))): fields = super(PermBaseModelAdmin, self).get_fields(request, obj) excluded_fields = self.get_excluded_fields() readonly_fields = self.get_readonly_fields(request, obj) new_fields = [ i for i in flatten(fields) if i in readonly_fields and i not in excluded_fields ] return new_fields else: return super(PermBaseModelAdmin, self).get_fields(request, obj)
def handle(self, *args, **options): number = options.get('number') seeder = Seed.seeder() all_users = User.objects.all() room_types = RoomType.objects.all() amenities = Amenity.objects.all() facilities = Facility.objects.all() rules = HouseRule.objects.all() seeder.add_entity( Room, number, { 'name': lambda x: seeder.faker.address(), 'host': lambda x: random.choice(all_users), 'room_type': lambda x: random.choice(room_types), 'price': lambda x: random.randint(100, 10000) // 100 * 100, 'beds': lambda x: random.randint(1, 5), 'bedrooms': lambda x: random.randint(1, 5), 'baths': lambda x: random.randint(1, 5), 'guests': lambda x: random.randint(1, 10) }) created_rooms = seeder.execute() created_clean = flatten(list(created_rooms.values())) for pk in created_clean: room = Room.objects.get(pk=pk) for i in range(3, random.randint(10, 17)): Photo.objects.create( caption=seeder.faker.sentence(), room=room, file=f'rooms_photos/{random.randint(1,31)}.webp', ) for a in amenities: idx = random.randint(0, 15) if idx % 2 == 0: room.amenities.add(a) for f in facilities: idx = random.randint(0, 15) if idx % 2 == 0: room.facilities.add(f) for r in rules: idx = random.randint(0, 15) if idx % 2 == 0: room.house_rules.add(r) self.stdout.write(self.style.SUCCESS(f'{number} rooms are created!'))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() all_users = user_models.User.objects.all() instrument = ad_models.instrumentChoice.objects.all() seeder.add_entity( ad_models.Advertisement, number, { "student": lambda x: random.choice(all_users), "instrument": lambda x: random.choice(instrument), "min_fee": lambda x: random.randint(10000, 30000), "max_fee": lambda x: random.randint(30000, 100000), }, ) created_ads = seeder.execute() created_clean = flatten(list(created_ads.values())) desired_lesson_days = ad_models.LessonDay.objects.all() lesson_type = ad_models.LessonType.objects.all() prefer_style = ad_models.PreferStyle.objects.all() for pk in created_clean: advertisement = ad_models.Advertisement.objects.get(pk=pk) for d in desired_lesson_days: magic_number = random.randint(0, 10) if magic_number % 2 == 0: advertisement.desired_lesson_days.add(d) for t in lesson_type: magic_number = random.randint(0, 10) if magic_number % 2 == 0: advertisement.lesson_type.add(t) for p in prefer_style: magic_number = random.randint(0, 10) if magic_number % 2 == 0: advertisement.prefer_style.add(p) self.stdout.write( self.style.SUCCESS(f"{number} students' ads created!"))
def _check_fieldsets_item(self, cls, model, fieldset, label): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ if not isinstance(fieldset, (list, tuple)): return must_be('a list or tuple', option=label, obj=cls, id='admin.E008') elif len(fieldset) != 2: return must_be('a pair', option=label, obj=cls, id='admin.E009') elif not isinstance(fieldset[1], dict): return must_be('a dictionary', option='%s[1]' % label, obj=cls, id='admin.E010') elif 'fields' not in fieldset[1]: return [ checks.Error( '"%s[1]" must contain "fields" key.' % label, hint=None, obj=cls, id='admin.E011', ) ] fields = flatten(fieldset[1]['fields']) if len(fields) != len(set(fields)): return [ checks.Error( 'There are duplicate field(s) in "%s[1]".' % label, hint=None, obj=cls, id='admin.E012', ) ] return list( chain(*[ self._check_field_spec(cls, model, fieldset_fields, '%s[1][\'fields\']' % label) for fieldset_fields in fieldset[1]['fields'] ]))
def handle(self, *args, **options): """ The actual logic of the command. Subclasses must implement this method. """ times = options.get('times') seeder = Seed.seeder() seeder.add_entity( models.Realtor, times, { 'name': lambda x: seeder.faker.name(), 'description': lambda x: seeder.faker.paragraph(), 'phone': lambda x: seeder.faker.phone_number(), 'email': lambda x: seeder.faker.email(), 'avater': lambda x: f'avater/{random.randint(0,6)}.jpg', }) created_reol = seeder.execute() clean_rel = flatten(list(created_reol.values())) print(clean_rel) self.stdout.write( self.style.SUCCESS(f'this code run for {times} Successfully '))
def handle(self, *args, **options): users = get_user_model().objects.all() rooms = Room.objects.all() number = options.get("number") seeder = Seed.seeder() seeder.add_entity( List, number, { "user": lambda x: random.choice(users), "name": lambda x: seeder.faker.name(), }, ) new_lists = seeder.execute() list_pk_list = flatten(new_lists.values()) for list_pk in list_pk_list: new_list = List.objects.get(pk=list_pk) room_in_list = random.sample(list(rooms), k=random.randint(3, 8)) new_list.rooms.add(*room_in_list) print(f"{number}개의 리스트를 만들었습니다.")
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() all_users = user_models.User.objects.all() seeder.add_entity( list_models.List, number, { "name": lambda x: seeder.faker.address(), "user": lambda x: random.choice(all_users), }, ) seeder_pk = seeder.execute() for pk in flatten(seeder_pk.values()): lists = list_models.List.objects.get(pk=pk) room = room_models.Room.objects.all() to_add = room[random.randint(0, 5):random.randint(6, 10)] # "*" means I wanna use only data in array, not array type data lists.room.add(*to_add) self.stdout.write(self.style.SUCCESS(f"{number} {NAME} created!"))
def handle(self, *args, **options): number = options.get('number') seeder = Seed.seeder() users = User.objects.all() rooms = Room.objects.all() seeder.add_entity(List, number, { "user": lambda x: random.choice(users), },) created = seeder.execute() created_clean = flatten(list(created.values())) for pk in created_clean: list_model = List.objects.get(pk=pk) to_add = rooms[random.randint(0, 5): random.randint(6, 30)] list_model.rooms.add(*to_add) self.stdout.write(self.style.SUCCESS("Lists created!"))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() Signature_Type = SignatureType.objects.all() seeder.add_entity( Signature, number, { "name": lambda x: seeder.faker.name(), "price": lambda x: random.randint(10000, 50000), }, ) create_something = seeder.execute() create_clean = flatten(list(create_something.values())) for pk in create_clean: signature = Signature.objects.get(pk=pk) a = random.choice(Signature_Type) signature.signature_type.add(a) self.stdout.write(self.style.SUCCESS(f"{number} Signature created!"))
def locale_count(self): result = super().get_queryset().filter( Q(employmentstatus='Active') | Q(employmentstatus='Leave of Absence') | Q(employmentstatus='Future Start')).values( 'department', 'state').annotate(count=Count('state')).distinct() output = defaultdict(dict) for dept in result: output[dept['department']][dept['state']] = dept['count'] localesDict = dict(output) s = [] for k, v in localesDict.items(): states = list(v.keys()) s.append(states) output = flatten(s) statesList = list(set(output)) statesList.sort() return localesDict, statesList
def handle(self, *args, **options): number = options.get( "number", 1 ) # The number typed after '--number'. The number is default=2 according to the above method. seeder = Seed.seeder() users = user_models.User.objects.all() rooms = room_models.Room.objects.all() seeder.add_entity( list_models.List, number, {"user": lambda x: random.choice(users),}, ) created = seeder.execute() cleaned = flatten(list(created.values())) for pk in cleaned: one_list = list_models.List.objects.get(pk=pk) # rooms[2:5] : get rooms from the list #2 to 5. to_add = rooms[random.randint(0, 5) : random.randint(6, 30)] one_list.rooms.add(*to_add) # to add many-to-many field: add() # *to_add gets the actual rooms not query set self.stdout.write(self.style.SUCCESS(f"{number} {NAME} created!"))
def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() users = user_models.User.objects.all() rooms = room_models.Room.objects.all() seeder.add_entity( list_models.List, number, {"user": lambda x: random.choice(users)}, ) created_list = seeder.execute() # Image Fake 할당 # 생성된 Data의 pk list를 리턴 함 created_clean = flatten(list(created_list.values())) for pk in created_clean: list_model = list_models.List.objects.get(pk=pk) for k in random.choices(list(rooms), k=random.randint(3, 20)): list_model.rooms.add(k) self.stdout.write(self.style.SUCCESS(f"{number} Lists Created!"))
# -*- coding: utf-8 -*-