def test_m2m_db_constraint(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) # Check that initial tables are there list(Author.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = ManyToManyField("schema.Tag", related_name="authors", db_constraint=False) new_field.contribute_to_class(Author, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field( Author, new_field, ) # Make sure no FK constraint is present constraints = self.get_constraints( new_field.rel.through._meta.db_table) for name, details in constraints.items(): if details['columns'] == ["tag_id"] and details['foreign_key']: self.fail("FK constraint for tag_id found")
def register(model, field_name=None, m2m=False): """ This registers the model class so it can have followers """ from models import Follow if model in registry: return registry.append(model) related_name = 'follow_%s' % model._meta.module_name if not field_name: field_name = model._meta.module_name # Create foreignkeys by default - less sql queries for lookups if m2m: field = ManyToManyField( model, related_name=related_name, ) else: field = ForeignKey( model, related_name=related_name, blank=True, null=True, ) field.contribute_to_class(Follow, field_name) setattr(model, 'followers', followers_for_object) # We need to keep track of which fields and which kind of fields point where model_map[model] = [related_name, field_name, m2m]
class Manga(TimeStampedModel, ReprMixin, models.Model): name = TextField("manga_name", null=True, blank=True) self_url = URLField("manga_url", max_length=1000, unique=True) description = TextField("manga_description") status = TextField("status", null=True, blank=True) year = TextField("year", null=True, blank=True) image_url = URLField("image_url", default="") # There can be manga with no chapters, i.e. future releases chapters = models.JSONField(default=dict) genres = ManyToManyField("Genre", related_name="mangas") categories = ManyToManyField("Category", related_name="mangas") author = ForeignKey("Author", related_name="mangas", on_delete=models.SET_NULL, null=True, blank=True) illustrators = ManyToManyField("Illustrator", related_name="mangas") screenwriters = ManyToManyField("Screenwriter", related_name="mangas") translators = ManyToManyField("Translator", related_name="mangas") technical_params = models.JSONField(default=dict)
def test_m2m(self): """ Tests adding/removing M2M fields on models """ # Create the tables with connection.schema_editor() as editor: editor.create_model(AuthorWithM2M) editor.create_model(TagM2MTest) # Create an M2M field new_field = ManyToManyField("schema.TagM2MTest", related_name="authors") new_field.contribute_to_class(AuthorWithM2M, "tags") try: # Ensure there's no m2m table there self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through) # Add the field with connection.schema_editor() as editor: editor.add_field( Author, new_field, ) # Ensure there is now an m2m table there columns = self.column_classes(new_field.rel.through) self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField") # Remove the M2M table again with connection.schema_editor() as editor: editor.remove_field( Author, new_field, ) # Ensure there's no m2m table there self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through) finally: # Cleanup model states AuthorWithM2M._meta.local_many_to_many.remove(new_field)
class User(AbstractUser): follows = ManyToManyField("User", blank=True, related_name="followers") likes = ManyToManyField("Post", blank=True, related_name="likers") year = models.IntegerField(blank=True, null=True) picture = models.TextField(blank=True) gender = models.TextField(blank=True) american_indian_or_alaska_native = models.BooleanField(blank=True, default=False) asian = models.BooleanField(blank=True, default=False) black_or_african_american = models.BooleanField(blank=True, default=False) hispanic_or_latino = models.BooleanField(blank=True, default=False) middle_eastern = models.BooleanField(blank=True, default=False) native_hawaiian_or_other_pacific_islander = models.BooleanField( blank=True, default=False) white = models.BooleanField(blank=True, default=False) other = models.BooleanField(blank=True, default=False) major = models.TextField(blank=True) minor = models.TextField(blank=True) modification = models.TextField(blank=True) birthday = models.DateField(blank=True, null=True) role = models.TextField(blank=True) home = models.TextField(blank=True) quote = models.TextField(blank=True) favorite_shoe = models.TextField(blank=True) favorite_artist = models.TextField(blank=True) favorite_color = models.TextField(blank=True) phoneType = models.TextField(blank=True)
def test_m2m_through_alter(self): """ Tests altering M2Ms with explicit through models (should no-op) """ # Create the tables with connection.schema_editor() as editor: editor.create_model(AuthorTag) editor.create_model(AuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(AuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. with connection.schema_editor() as editor: old_field = AuthorWithM2MThrough._meta.get_field_by_name("tags")[0] new_field = ManyToManyField("schema.TagM2MTest", related_name="authors", through="AuthorTag") new_field.contribute_to_class(AuthorWithM2MThrough, "tags") editor.alter_field( Author, old_field, new_field, ) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(AuthorTag)), 3)
def register(model, field_name = None, m2m = False): """ This registers the model class so it can have followers """ from models import Follow if model in registry: return registry.append(model) related_name = 'follow_%s' % model._meta.module_name if not field_name: field_name = model._meta.module_name # Create foreignkeys by default - less sql queries for lookups if m2m: field = ManyToManyField( model, related_name = related_name, ) else: field = ForeignKey( model, related_name = related_name, blank = True, null = True, ) field.contribute_to_class(Follow, field_name) setattr(model, 'followers', followers_for_object) # We need to keep track of which fields and which kind of fields point where model_map[model] = [related_name, field_name, m2m]
def test_m2m_repoint(self): """ Tests repointing M2M fields """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest constraints = connection.introspection.get_constraints( connection.cursor(), BookWithM2M._meta.get_field_by_name("tags") [0].rel.through._meta.db_table) if connection.features.supports_foreign_keys: for name, details in constraints.items(): if details['columns'] == ["tagm2mtest_id" ] and details['foreign_key']: self.assertEqual(details['foreign_key'], ('schema_tagm2mtest', 'id')) break else: self.fail("No FK constraint for tagm2mtest_id found") # Repoint the M2M new_field = ManyToManyField(UniqueTest) new_field.contribute_to_class(BookWithM2M, "uniques") try: with connection.schema_editor() as editor: editor.alter_field( Author, BookWithM2M._meta.get_field_by_name("tags")[0], new_field, ) # Ensure old M2M is gone self.assertRaises( DatabaseError, self.column_classes, BookWithM2M._meta.get_field_by_name("tags")[0].rel.through) # Ensure the new M2M exists and points to UniqueTest constraints = connection.introspection.get_constraints( connection.cursor(), new_field.rel.through._meta.db_table) if connection.features.supports_foreign_keys: for name, details in constraints.items(): if details['columns'] == ["uniquetest_id" ] and details['foreign_key']: self.assertEqual(details['foreign_key'], ('schema_uniquetest', 'id')) break else: self.fail("No FK constraint for uniquetest_id found") finally: # Cleanup through table separately with connection.schema_editor() as editor: editor.remove_field( BookWithM2M, BookWithM2M._meta.get_field_by_name("uniques")[0]) # Cleanup model states BookWithM2M._meta.local_many_to_many.remove(new_field) del BookWithM2M._meta._m2m_cache
class Tag(models.Model): article = ManyToManyField(Article) user = ManyToManyField(User) tag_key = models.CharField(unique=True, blank=True, null=True, max_length=100) tag_value = models.CharField(blank=True, null=True, max_length=100)
class Atractivo(models.Model): tipo = OneToOneField(Tipo, on_delete=CASCADE, blank=False) zona = OneToOneField(Zona, on_delete=CASCADE, blank=False) categorias = ManyToManyField(Categoria, blank=False) servicios = ManyToManyField(Servicio, blank=False) nombre = CharField(max_length=100, null=False, blank=False) direccion = CharField(max_length=100, null=False, blank=False) descripcion = CharField(max_length=600, null=False, blank=False) def __str__(self): return self.nombre
class UserProfile(Model): user = OneToOneField(User) lessons = ManyToManyField(Lesson, null=True, default=None, blank=True) badges = ManyToManyField(Badge, null=True, default=None, blank=True) goals = ManyToManyField(Goal, null=True, default=None, blank=True) posts = ManyToManyField(Post, null=True, default=None, blank=True) def __str__(self): return self.user.email + " profile" def __unicode__(self): return self.user.email + " profile"
class CaThiTuLuan(models.Model): ten_ca_thi = CharField(max_length=100, verbose_name="Tiêu đề ca thi") nam_hoc = CharField(max_length=9, verbose_name="Năm học", help_text="Nhập năm học theo định dạng XXXX-XXXX. Ví dụ 2015-2016") hoc_ky = CharField(max_length=3, choices=HOC_KY, default=HK1, verbose_name="Học kỳ") doi_tuong = ForeignKey(DoiTuong, verbose_name="Đối tượng") mon_thi = ForeignKey(MonThi, verbose_name = "Môn thi") lop = ForeignKey(Lop, verbose_name = "Lớp") ngay_thi = DateField(verbose_name="Ngày thi") # giam_thi = ManyToManyField(GiaoVien, blank=False, verbose_name=u'Danh sách giám thị coi thi') # giam_thi = ManyToManyField(GiaoVien, blank=False, # verbose_name = u'GT') so_de_thi = PositiveIntegerField(verbose_name = "Số đề thi", default=1, help_text = u"Số đề thi là số nguyên dương, lớn hơn 0") ds_de_thi = ManyToManyField(DeThiTuLuan, blank=True, verbose_name = u'DT') class Meta: verbose_name = u"Kế hoạch thi - bốc đề" verbose_name_plural = u"Kế hoạch thi - bốc đề" def __unicode__(self): return u'%s-%s-%s' %(self.doi_tuong, self.mon_thi, self.lop) # def save(self, *args, **kwargs): # # lay ngan hang de thi tuong ung voi doi_tuong va mon_thi # ngan_hang_dt = NganHangDeThiTuLuan.objects.filter(doi_tuong=self.doi_tuong, # mon_thi=self.mon_thi) # # lay so_de_thi # de_thi_s = random.sample(ngan_hang_dt, self.so_de_thi) # for de_thi in de_thi_s: # self.ds_de_thi.add(de_thi) # super(CaThiTuLuan, self).save(*args, **kwargs)
def __init__(self, to, chained_field=None, chained_model_field=None, show_all=False, auto_choose=False, view_name=None, **kwargs): if isinstance(to, basestring): self.app_name, self.model_name = to.split('.') else: self.app_name = to._meta.app_label self.model_name = to._meta.object_name self.chain_field = chained_field self.model_field = chained_model_field self.show_all = show_all self.auto_choose = auto_choose self.view_name = view_name ManyToManyField.__init__(self, to, **kwargs)
def __init__(self, to, **kwargs): ManyToManyFieldOriginal.__init__(to, **kwargs) self.model = None self.query_field_name = '' self.core_filters = {} self.instance = None self.symmetrical = None self.source_field = None self.source_field_name = '' self.target_field_name = '' self.reverse = None self.through = None self.prefetch_cache_name = None self.related_val = None
class Assembly(MPTTModel,TitleSlugDescriptionModel,TimeStampedModel): type = ForeignKey("AssemblyType",related_name="assemblies") parent = TreeForeignKey("self",blank=True,null=True,related_name="children") leaders = ManyToManyField(User,blank=True,null=True, related_name='assemblies_lead') learners = ManyToManyField(User,blank=True,null=True, related_name='assemblies_attended') units = ManyToManyField(Unit,blank=True,null=True,related_name='assemblies',through='ScheduleEntry') objects = tree = TreeManager() class Meta: verbose_name_plural = "assemblies" def __unicode__(self): return self.title
def test_m2m_repoint(self): """ Tests repointing M2M fields """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest constraints = connection.introspection.get_constraints( connection.cursor(), BookWithM2M._meta.get_field_by_name("tags")[0].rel.through._meta.db_table ) if connection.features.supports_foreign_keys: for name, details in constraints.items(): if details["columns"] == ["tagm2mtest_id"] and details["foreign_key"]: self.assertEqual(details["foreign_key"], ("schema_tagm2mtest", "id")) break else: self.fail("No FK constraint for tagm2mtest_id found") # Repoint the M2M new_field = ManyToManyField(UniqueTest) new_field.contribute_to_class(BookWithM2M, "uniques") try: with connection.schema_editor() as editor: editor.alter_field(Author, BookWithM2M._meta.get_field_by_name("tags")[0], new_field) # Ensure old M2M is gone self.assertRaises( DatabaseError, self.column_classes, BookWithM2M._meta.get_field_by_name("tags")[0].rel.through ) # Ensure the new M2M exists and points to UniqueTest constraints = connection.introspection.get_constraints( connection.cursor(), new_field.rel.through._meta.db_table ) if connection.features.supports_foreign_keys: for name, details in constraints.items(): if details["columns"] == ["uniquetest_id"] and details["foreign_key"]: self.assertEqual(details["foreign_key"], ("schema_uniquetest", "id")) break else: self.fail("No FK constraint for uniquetest_id found") finally: # Cleanup through table separately with connection.schema_editor() as editor: editor.remove_field(BookWithM2M, BookWithM2M._meta.get_field_by_name("uniques")[0]) # Cleanup model states BookWithM2M._meta.local_many_to_many.remove(new_field) del BookWithM2M._meta._m2m_cache
class BoardGame(models.Model): # main id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=256) description = models.TextField(blank=True, null=True) image_url = models.URLField(max_length=500, blank=True, null=True) year_published = models.FloatField(blank=True, null=True) min_playtime = models.FloatField(blank=True, null=True) max_playtime = models.FloatField(blank=True, null=True) min_number_of_players = models.FloatField(blank=True, null=True) max_number_of_players = models.FloatField(blank=True, null=True) min_age = models.FloatField(blank=True, null=True) # Relations author = ManyToManyField(Author, through='BoardgameAuthor') publisher = ManyToManyField(Publisher, through='BoardgamePublisher') game_mechanic = ManyToManyField(GameMechanic, through='BoardgameMechanic') category = ManyToManyField(Category, through='BoardgameCategory') # Recommendations user_recommendations = models.ManyToManyField(User, through='Recommendations') # BGG stuff bgg_id = models.FloatField(blank=True, null=True) bgg_avg_rating = models.FloatField(blank=True, null=True) bgg_num_ratings = models.FloatField(blank=True, null=True) bgg_avg_bayes = models.FloatField(blank=True, null=True) bgg_rank = models.FloatField(blank=True, null=True) bgg_stddev = models.FloatField(blank=True, null=True) bgg_num_user_comments = models.FloatField(blank=True, null=True) # BGA stuff bga_id = models.CharField(max_length=256, blank=True, null=True) bga_avg_rating = models.FloatField(blank=True, null=True) bga_num_ratings = models.FloatField(blank=True, null=True) bgg_average_weight = models.FloatField(blank=True, null=True) bga_url = models.URLField(max_length=500, blank=True, null=True) bga_rank = models.FloatField(blank=True, null=True) bga_rank_trending = models.FloatField(blank=True, null=True) bga_price_us = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) # others thumbnail_url = models.URLField(max_length=500, blank=True, null=True) official_url = models.URLField(max_length=500, blank=True, null=True) reddit_all_time_count = models.FloatField(blank=True, null=True)
class Character(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) name = models.CharField(max_length=15) race = models.ForeignKey("Race", on_delete=models.CASCADE) classCharacter = models.ForeignKey("Class", on_delete=models.CASCADE) subclass = models.ForeignKey("Subclass", on_delete=models.CASCADE, null=True) level = models.IntegerField(validators=[MinValueValidator(0)]) strength = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(20)]) dexterity = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(20)]) constitution = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(20)]) intelligence = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(20)]) wisdom = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(20)]) charisma = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(20)]) maxHP = models.IntegerField(validators=[MinValueValidator(0)]) armorClass = models.IntegerField(validators=[MinValueValidator(0)]) spells = ManyToManyField("Spell") def __str__(self): return self.name
class Assignment(MPTTModel, TimeStampedModel): parent = TreeForeignKey("self", blank=True, null=True, related_name="children") worksheet = ForeignKey(Worksheet, related_name="assignments") unit = ForeignKey("Unit", related_name="assignments") start = DateTimeField(blank=True, null=True) end = DateTimeField(blank=True, null=True) hide_until_start = BooleanField(default=False) users = ManyToManyField(User, related_name="assignments", through="Engagement") objects = tree = TreeManager() def __unicode__(self): name = "%s assigned for %s %s" % (self.worksheet, self.unit.type, self.unit) if self.start: name += " starting %s" % (self.start) if self.end: name += " until %s" % (self.end) return name
class Manga(TimeStampedModel, models.Model): title = TextField("manga_title", unique=True, db_index=True) description = TextField("manga_description") status = TextField("status", null=True, blank=True) year = TextField("year", null=True, blank=True) image_url = TextField("url", default="") # There can be manga with no chapters, i.e. future releases chapters = HStoreField(null=True, blank=True) genres = ManyToManyField("Genre", related_name="mangas") author = ForeignKey("Author", related_name="mangas", on_delete=models.CASCADE, null=True, blank=True) translators = ManyToManyField("Translator", related_name="mangas")
class StoredBasket(models.Model): # A combination of the PK and key is used to retrieve a basket for session situations. key = models.CharField(max_length=32, default=generate_key) owner_contact = models.ForeignKey("shoop.Contact", blank=True, null=True) owner_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True, db_index=True, editable=False) updated_on = models.DateTimeField(auto_now=True, db_index=True, editable=False) persistent = models.BooleanField(db_index=True, default=False) deleted = models.BooleanField(db_index=True, default=False) finished = models.BooleanField(db_index=True, default=False) title = models.CharField(max_length=64, blank=True) data = TaggedJSONField() # For statistics etc., as `data` is opaque: taxless_total = MoneyField(default=0, null=True, blank=True) taxful_total = MoneyField(default=0, null=True, blank=True) product_count = models.IntegerField(default=0) products = ManyToManyField("shoop.Product", blank=True) class Meta: app_label = "shoop_front"
class Author(models.Model): first_name = CharField(max_length=45) last_name = CharField(max_length=45) notes = TextField(default=None) created_at = DateTimeField(auto_now_add=True) updated_at = DateTimeField(auto_now=True) books = ManyToManyField(Book, related_name="authors")
class Case(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created") assigned = models.ForeignKey(User, on_delete=models.CASCADE, related_name="assigned") patient_name = models.CharField(max_length=100) patient_surname = models.CharField(max_length=100) prediagnosis = models.CharField(max_length=200) message = ManyToManyField(Message, blank=True, related_name="case_message") closed = models.BooleanField(default=False) room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='cases') timestamp = models.DateTimeField(auto_now_add=True, blank=False) def serialize(self, request_user): return { "id": self.id, "creator": self.creator.username, "can_record": self.assigned == request_user, "patient_name": self.patient_name, "patient_surname": self.patient_surname, "prediagnosis": self.prediagnosis, "recordings": [r.recording.url for r in self.recordings.all()], "closed": self.closed, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p") }
def __init__(self, to, chained_field=None, chained_model_field=None, auto_choose=False, **kwargs): """ examples: class Publication(models.Model): name = models.CharField(max_length=255) class Writer(models.Model): name = models.CharField(max_length=255) publications = models.ManyToManyField('Publication', blank=True, null=True) class Book(models.Model): publication = models.ForeignKey(Publication) writer = ChainedManyToManyField( Writer, chained_field="publication", chained_model_field="publications", ) name = models.CharField(max_length=255) ``chained_field`` is the name of the ForeignKey field referenced by ChainedManyToManyField of the same Model. in the examples, chained_field is the name of field publication in Model Book. ``chained_model_field`` is the name of the ManyToMany field referenced in the 'to' Model. in the examples, chained_model_field is the name of field publications in Model Writer. ``auto_choose`` controls whether auto select the choice when there is only one available choice. """ try: isbasestring = isinstance(to, basestring) except NameError: isbasestring = isinstance(to, str) if isbasestring: self.to_app_name, self.to_model_name = to.split('.') else: self.to_app_name = to._meta.app_label self.to_model_name = to._meta.object_name self.chain_field = chained_field self.chained_model_field = chained_model_field self.auto_choose = auto_choose ManyToManyField.__init__(self, to, **kwargs)
class RegistroVotacao(models.Model): tipo_resultado_votacao = models.ForeignKey( TipoResultadoVotacao, on_delete=models.PROTECT, verbose_name=_('Resultado da Votação')) materia = models.ForeignKey(MateriaLegislativa, on_delete=models.CASCADE) ordem = models.ForeignKey(OrdemDia, blank=True, null=True, related_name="registrovotacao_set", on_delete=models.CASCADE) expediente = models.ForeignKey(ExpedienteMateria, blank=True, null=True, on_delete=models.CASCADE) numero_votos_sim = models.PositiveIntegerField(verbose_name=_('Sim')) numero_votos_nao = models.PositiveIntegerField(verbose_name=_('Não')) numero_abstencoes = models.PositiveIntegerField( verbose_name=_('Abstenções')) observacao = models.TextField(blank=True, verbose_name=_('Observações')) subscricoes = ManyToManyField(Parlamentar, related_name='subscricoes') user = models.ForeignKey(get_settings_auth_user_model(), on_delete=models.PROTECT, null=True, blank=True) ip = models.CharField(verbose_name=_('IP'), max_length=30, blank=True, default='') data_hora = models.DateTimeField(verbose_name=_('Data/Hora'), auto_now_add=True, blank=True, null=True) class Meta: verbose_name = _('Votação') verbose_name_plural = _('Votações') ordering = ('id', ) def __str__(self): return _('Ordem: %(ordem)s - Votação: %(votacao)s - ' 'Matéria: %(materia)s') % { 'ordem': self.ordem, 'votacao': self.tipo_resultado_votacao, 'materia': self.materia } def clean(self): """Exatamente um dos campos ordem ou expediente deve estar preenchido. """ # TODO remover esse método quando OrdemDia e ExpedienteMateria # forem reestruturados e os campos ordem e expediente forem unificados if not xor(bool(self.ordem), bool(self.expediente)): raise ValidationError( 'RegistroVotacao deve ter exatamente um dos campos ' 'ordem ou expediente preenchido. Ambos estão preenchidos: ' '{}, {}'.format(self.ordem, self.expediente))
class Counter_Offer(models.Model): class Meta: permissions = (('CAN_VIEW','Can view public instances'),) cards = ManyToManyField(Pokemon) trade = models.ForeignKey('Trade',on_delete=models.PROTECT,null=True) creator = ForeignKey(User, on_delete=models.CASCADE)
class Schedule(Model): sections = ManyToManyField(Section, blank=True) start_time = TimeField(default=datetime.time(7)) end_time = TimeField(default=datetime.time(22)) def __unicode__(self): return "Schedule (%s)" % unicode(self.id)
class AfterHoursActivityForm(forms.Form): member = CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) reason = forms.CharField(max_length=500) completed = forms.BooleanField, did_you_clean_up_after = forms.BooleanField(required=True), tidied_up = ManyToManyField(AfterHoursTidiness) are_there_dishes = forms.BooleanField(required=False),
class Cursos(models.Model): users = ManyToManyField(CustomUsuarios) nombreCurso = models.CharField(max_length=50, default='any') tutorCurso = models.CharField(max_length=50, default='any') fechaCurso = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return f'Cursos: {self.nombreCurso}'
class Worksheet(ContentModel): instructions = TextField(blank=True, null=True) background = ImageField(upload_to="lessons/worksheets/backgrounds/") field_data = json.JSONField(blank=True, null=True) related_content = ManyToManyField(RelatedContent, blank=True, null=True, related_name='worksheets')
class Materias(models.Model): users = ManyToManyField(CustomUsuarios) nombreMateria = models.CharField(max_length=50, default='any') tutorMateria = models.CharField(max_length=50, default='any') califs = models.IntegerField(default=70) fechaCalifs = models.DateTimeField(auto_now=False, null=True, blank=True) def __str__(self): return f'Materias : {self.nombreMateria} {self.tutorMateria}'
class BookModel(Model): title = CharField(max_length=100) publishers = ManyToManyField(PublisherModel, related_name='books') class Meta: db_table = 'books' def __unicode__(self): return unicode(self.title)
class Quiz(Model): name = CharField(max_length=50) questions = ManyToManyField(Question) def __str__(self): return self.name def __unicode__(self): return self.name
def test_m2m_db_constraint(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) # Check that initial tables are there list(Author.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = ManyToManyField("schema.Tag", related_name="authors", db_constraint=False) new_field.contribute_to_class(Author, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Make sure no FK constraint is present constraints = self.get_constraints(new_field.rel.through._meta.db_table) for name, details in constraints.items(): if details["columns"] == ["tag_id"] and details["foreign_key"]: self.fail("FK constraint for tag_id found")
def test_m2m_through_alter(self): """ Tests altering M2Ms with explicit through models (should no-op) """ # Create the tables with connection.schema_editor() as editor: editor.create_model(AuthorTag) editor.create_model(AuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(AuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. with connection.schema_editor() as editor: old_field = AuthorWithM2MThrough._meta.get_field_by_name("tags")[0] new_field = ManyToManyField("schema.TagM2MTest", related_name="authors", through="AuthorTag") new_field.contribute_to_class(AuthorWithM2MThrough, "tags") editor.alter_field(Author, old_field, new_field) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(AuthorTag)), 3)
def register(model, field_name = None, m2m = False): """ This registers the model class so it can have followers, adds a method to the model ``get_followers``, returning the followers - a query set of ``:class:auth.models.User`` objects """ if model in registry: return registry.append(model) related_name = 'follow_%s' % model._meta.module_name # Create foreignkeys by default - less sql queries for lookups if m2m: field = ManyToManyField( model, related_name = related_name, ) else: field = ForeignKey( model, related_name = related_name, blank = True, null = True, ) if not field_name: field_name = model._meta.module_name from models import Follow field.contribute_to_class(Follow, field_name) model.add_to_class('get_followers', get_followers_for_object) # We need to keep track of which fields and which kind of fields point where model_map[model] = [related_name, field_name, m2m]
template = '%(expressions)s' arg_joiner = ' - ' arity = 2 def __init__(self, start, end): super(DateDiff, self).__init__(start, end) def as_microsoft(self, compiler, connection): self.template = 'cast(DateDiff(day,%(expressions)s) as float)* -1 *24*60*60*1000.0*1000.0' # Convert to microseconds as used by Django DurationField' self.arg_joiner = ', ' return super(DateDiff, self).as_sql(compiler, connection) def as_sql(self, compiler, connection, function=None, template=None): if connection.vendor is 'microsoft': return self.as_microsoft(compiler, connection) return super(DateDiff, self).as_sql(compiler, connection) class NotEqual(Lookup): lookup_name = 'ne' def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return '%s != %s' % (lhs, rhs), params Field.register_lookup(NotEqual) RelatedField.register_lookup(NotEqual) ForeignObject.register_lookup(NotEqual) ManyToManyField.register_lookup(NotEqual)
def __init__(self, translated_field, language, to, *args, **kwargs): self._related_pre_init(translated_field, language, *args, **kwargs) ManyToManyField.__init__(self, to, **kwargs) self._related_post_init()