だから私はこのような2つのモデルを持っています。
class Channel(BaseModel):
class Meta:
verbose_name = 'channel'
verbose_name_plural = 'channels'
indexes = [
models.Index(fields=['box', 'name'], name='channel_box_name_idx'),
]
def __str__(self):
return self.name
def get_next_position(self):
aggregate = self.box.channels.aggregate(models.Max('position'))
return (aggregate['position__max'] or -1) + 1
def save(self, *args, **kwargs):
if self._state.adding:
# we insert the object's position if
# it hasn't been created yet. We need to do
# this explicitly because django doesn't
# allow more than one auto-field
self.position = self.get_next_position()
super(Channel, self).save(*args, **kwargs)
return self.box.channels.add(self)
super(Channel, self).save(*args, **kwargs)
objects = models.Manager()
name = models.CharField(max_length=100, validators=[MinLengthValidator(2)])
box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE)
position = models.PositiveSmallIntegerField(db_index=True)
REQUIRED_FIELDS = [name, box]
class Box(BaseModel):
class Meta:
verbose_name = 'box'
verbose_name_plural = 'boxes'
indexes = [
models.Index(fields=['owner'], name='box_owner_idx'),
models.Index(fields=['owner', 'name'], name='box_name_owner_idx'),
]
def __str__(self):
return self.name
objects = models.Manager()
icon = models.ImageField(upload_to='icons/', storage=DefaultStorage)
name = models.CharField(max_length=100, validators=[MinLengthValidator(2)])
owner = models.ForeignKey('api_backend.User', on_delete=models.CASCADE)
channels = models.ManyToManyField('api_backend.Channel', related_name='box_channels')
REQUIRED_FIELDS = [name, owner]
チャネルには属性がありますbox
。そして、ボックスにはm2mフィールドがありますchannels
。したがって、このタイプの関係では、ボックスを使用してチャネルを作成するたびに、ボックスのm2mフィールドに同じものを追加する必要がありますchannels
。このようなものは本当に必要ですか?m2mフィールド用に追加のテーブルが必要なように、channels
それがなくても、次のようにして同じテーブルにアクセスできます。box.channel_set
では、パフォーマンスに変化はありますか?モデルの構造を変更する必要がありますか?誰か助けてくれませんか?
チャネルに複数のボックスを含めることはできますか?はいの場合、aManyToManyField
が適切であり、ForeignKey
削除する必要があります
に関連するものが1つしかManyToManyField
ないため、aChannel
が不要な場合はBox
、ManyToManyField
を削除し、関連するアクセサーchannel_set
を使用する必要があります。
代わりにBox
名前が付けられたインスタンスに属性を設定したい場合は、に提供できる関連するにアクセスするために使用できます。channels
channel_set
Channel
related_name
ForeignKey
class Channel(BaseModel):
...
box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE, related_name='channels')
...
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加