Rename ImageAttachment.content_type to object_type

This commit is contained in:
Jeremy Stretch 2024-03-01 16:34:52 -05:00
parent ce6b2666a9
commit e0165539b3
11 changed files with 51 additions and 34 deletions

View File

@ -312,7 +312,7 @@ class TagSerializer(ValidatedModelSerializer):
class ImageAttachmentSerializer(ValidatedModelSerializer): class ImageAttachmentSerializer(ValidatedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='extras-api:imageattachment-detail') url = serializers.HyperlinkedIdentityField(view_name='extras-api:imageattachment-detail')
content_type = ContentTypeField( object_type = ContentTypeField(
queryset=ObjectType.objects.all() queryset=ObjectType.objects.all()
) )
parent = serializers.SerializerMethodField(read_only=True) parent = serializers.SerializerMethodField(read_only=True)
@ -320,7 +320,7 @@ class ImageAttachmentSerializer(ValidatedModelSerializer):
class Meta: class Meta:
model = ImageAttachment model = ImageAttachment
fields = [ fields = [
'id', 'url', 'display', 'content_type', 'object_id', 'parent', 'name', 'image', 'image_height', 'id', 'url', 'display', 'object_type', 'object_id', 'parent', 'name', 'image', 'image_height',
'image_width', 'created', 'last_updated', 'image_width', 'created', 'last_updated',
] ]
brief_fields = ('id', 'url', 'display', 'name', 'image') brief_fields = ('id', 'url', 'display', 'name', 'image')
@ -329,10 +329,10 @@ class ImageAttachmentSerializer(ValidatedModelSerializer):
# Validate that the parent object exists # Validate that the parent object exists
try: try:
data['content_type'].get_object_for_this_type(id=data['object_id']) data['object_type'].get_object_for_this_type(id=data['object_id'])
except ObjectDoesNotExist: except ObjectDoesNotExist:
raise serializers.ValidationError( raise serializers.ValidationError(
"Invalid parent object: {} ID {}".format(data['content_type'], data['object_id']) "Invalid parent object: {} ID {}".format(data['object_type'], data['object_id'])
) )
# Enforce model validation # Enforce model validation

View File

@ -318,11 +318,11 @@ class ImageAttachmentFilterSet(BaseFilterSet):
label=_('Search'), label=_('Search'),
) )
created = django_filters.DateTimeFilter() created = django_filters.DateTimeFilter()
content_type = ContentTypeFilter() object_type = ContentTypeFilter()
class Meta: class Meta:
model = ImageAttachment model = ImageAttachment
fields = ['id', 'content_type_id', 'object_id', 'name'] fields = ['id', 'object_type_id', 'object_id', 'name']
def search(self, queryset, name, value): def search(self, queryset, name, value):
if not value.strip(): if not value.strip():

View File

@ -179,10 +179,10 @@ class ExportTemplateFilterForm(SavedFiltersMixin, FilterForm):
class ImageAttachmentFilterForm(SavedFiltersMixin, FilterForm): class ImageAttachmentFilterForm(SavedFiltersMixin, FilterForm):
fieldsets = ( fieldsets = (
(None, ('q', 'filter_id')), (None, ('q', 'filter_id')),
(_('Attributes'), ('content_type_id', 'name',)), (_('Attributes'), ('object_type_id', 'name',)),
) )
content_type_id = ContentTypeChoiceField( object_type_id = ContentTypeChoiceField(
label=_('Content type'), label=_('Object type'),
queryset=ObjectType.objects.with_feature('image_attachments'), queryset=ObjectType.objects.with_feature('image_attachments'),
required=False required=False
) )

View File

@ -74,4 +74,19 @@ class Migration(migrations.Migration):
name='object_types', name='object_types',
field=models.ManyToManyField(related_name='saved_filters', to='core.objecttype'), field=models.ManyToManyField(related_name='saved_filters', to='core.objecttype'),
), ),
# Image attachments
migrations.RemoveIndex(
model_name='imageattachment',
name='extras_imag_content_94728e_idx',
),
migrations.RenameField(
model_name='imageattachment',
old_name='content_type',
new_name='object_type',
),
migrations.AddIndex(
model_name='imageattachment',
index=models.Index(fields=['object_type', 'object_id'], name='extras_imag_object__96bebc_idx'),
),
] ]

View File

@ -598,13 +598,13 @@ class ImageAttachment(ChangeLoggedModel):
""" """
An uploaded image which is associated with an object. An uploaded image which is associated with an object.
""" """
content_type = models.ForeignKey( object_type = models.ForeignKey(
to='contenttypes.ContentType', to='contenttypes.ContentType',
on_delete=models.CASCADE on_delete=models.CASCADE
) )
object_id = models.PositiveBigIntegerField() object_id = models.PositiveBigIntegerField()
parent = GenericForeignKey( parent = GenericForeignKey(
ct_field='content_type', ct_field='object_type',
fk_field='object_id' fk_field='object_id'
) )
image = models.ImageField( image = models.ImageField(
@ -626,12 +626,12 @@ class ImageAttachment(ChangeLoggedModel):
objects = RestrictedQuerySet.as_manager() objects = RestrictedQuerySet.as_manager()
clone_fields = ('content_type', 'object_id') clone_fields = ('object_type', 'object_id')
class Meta: class Meta:
ordering = ('name', 'pk') # name may be non-unique ordering = ('name', 'pk') # name may be non-unique
indexes = ( indexes = (
models.Index(fields=('content_type', 'object_id')), models.Index(fields=('object_type', 'object_id')),
) )
verbose_name = _('image attachment') verbose_name = _('image attachment')
verbose_name_plural = _('image attachments') verbose_name_plural = _('image attachments')
@ -646,9 +646,9 @@ class ImageAttachment(ChangeLoggedModel):
super().clean() super().clean()
# Validate the assigned object type # Validate the assigned object type
if self.content_type not in ObjectType.objects.with_feature('image_attachments'): if self.object_type not in ObjectType.objects.with_feature('image_attachments'):
raise ValidationError( raise ValidationError(
_("Image attachments cannot be assigned to this object type ({type}).").format(type=self.content_type) _("Image attachments cannot be assigned to this object type ({type}).").format(type=self.object_type)
) )
def delete(self, *args, **kwargs): def delete(self, *args, **kwargs):

View File

@ -174,8 +174,8 @@ class ImageAttachmentTable(NetBoxTable):
verbose_name=_('ID'), verbose_name=_('ID'),
linkify=False linkify=False
) )
content_type = columns.ContentTypeColumn( object_type = columns.ContentTypeColumn(
verbose_name=_('Content Type'), verbose_name=_('Object Type'),
) )
parent = tables.Column( parent = tables.Column(
verbose_name=_('Parent'), verbose_name=_('Parent'),
@ -193,10 +193,10 @@ class ImageAttachmentTable(NetBoxTable):
class Meta(NetBoxTable.Meta): class Meta(NetBoxTable.Meta):
model = ImageAttachment model = ImageAttachment
fields = ( fields = (
'pk', 'content_type', 'parent', 'image', 'name', 'image_height', 'image_width', 'size', 'created', 'pk', 'object_type', 'parent', 'image', 'name', 'image_height', 'image_width', 'size', 'created',
'last_updated', 'last_updated',
) )
default_columns = ('content_type', 'parent', 'image', 'name', 'size', 'created') default_columns = ('object_type', 'parent', 'image', 'name', 'size', 'created')
class SavedFilterTable(NetBoxTable): class SavedFilterTable(NetBoxTable):

View File

@ -548,7 +548,7 @@ class ImageAttachmentTest(
image_attachments = ( image_attachments = (
ImageAttachment( ImageAttachment(
content_type=ct, object_type=ct,
object_id=site.pk, object_id=site.pk,
name='Image Attachment 1', name='Image Attachment 1',
image='http://example.com/image1.png', image='http://example.com/image1.png',
@ -556,7 +556,7 @@ class ImageAttachmentTest(
image_width=100 image_width=100
), ),
ImageAttachment( ImageAttachment(
content_type=ct, object_type=ct,
object_id=site.pk, object_id=site.pk,
name='Image Attachment 2', name='Image Attachment 2',
image='http://example.com/image2.png', image='http://example.com/image2.png',
@ -564,7 +564,7 @@ class ImageAttachmentTest(
image_width=100 image_width=100
), ),
ImageAttachment( ImageAttachment(
content_type=ct, object_type=ct,
object_id=site.pk, object_id=site.pk,
name='Image Attachment 3', name='Image Attachment 3',
image='http://example.com/image3.png', image='http://example.com/image3.png',

View File

@ -693,7 +693,7 @@ class ImageAttachmentTestCase(TestCase, BaseFilterSetTests):
image_attachments = ( image_attachments = (
ImageAttachment( ImageAttachment(
content_type=site_ct, object_type=site_ct,
object_id=sites[0].pk, object_id=sites[0].pk,
name='Image Attachment 1', name='Image Attachment 1',
image='http://example.com/image1.png', image='http://example.com/image1.png',
@ -701,7 +701,7 @@ class ImageAttachmentTestCase(TestCase, BaseFilterSetTests):
image_width=100 image_width=100
), ),
ImageAttachment( ImageAttachment(
content_type=site_ct, object_type=site_ct,
object_id=sites[1].pk, object_id=sites[1].pk,
name='Image Attachment 2', name='Image Attachment 2',
image='http://example.com/image2.png', image='http://example.com/image2.png',
@ -709,7 +709,7 @@ class ImageAttachmentTestCase(TestCase, BaseFilterSetTests):
image_width=100 image_width=100
), ),
ImageAttachment( ImageAttachment(
content_type=rack_ct, object_type=rack_ct,
object_id=racks[0].pk, object_id=racks[0].pk,
name='Image Attachment 3', name='Image Attachment 3',
image='http://example.com/image3.png', image='http://example.com/image3.png',
@ -717,7 +717,7 @@ class ImageAttachmentTestCase(TestCase, BaseFilterSetTests):
image_width=100 image_width=100
), ),
ImageAttachment( ImageAttachment(
content_type=rack_ct, object_type=rack_ct,
object_id=racks[1].pk, object_id=racks[1].pk,
name='Image Attachment 4', name='Image Attachment 4',
image='http://example.com/image4.png', image='http://example.com/image4.png',
@ -735,13 +735,13 @@ class ImageAttachmentTestCase(TestCase, BaseFilterSetTests):
params = {'name': ['Image Attachment 1', 'Image Attachment 2']} params = {'name': ['Image Attachment 1', 'Image Attachment 2']}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_content_type(self): def test_object_type(self):
params = {'content_type': 'dcim.site'} params = {'object_type': 'dcim.site'}
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2) self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
def test_content_type_id_and_object_id(self): def test_object_type_id_and_object_id(self):
params = { params = {
'content_type_id': ContentType.objects.get(app_label='dcim', model='site').pk, 'object_type_id': ContentType.objects.get(app_label='dcim', model='site').pk,
'object_id': [Site.objects.first().pk], 'object_id': [Site.objects.first().pk],
} }
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1) self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)

View File

@ -24,7 +24,7 @@ def image_upload(instance, filename):
elif instance.name: elif instance.name:
filename = instance.name filename = instance.name
return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename) return '{}{}_{}_{}'.format(path, instance.object_type.name, instance.object_id, filename)
def is_script(obj): def is_script(obj):

View File

@ -329,7 +329,9 @@ class ImageAttachmentsMixin(models.Model):
Enables the assignments of ImageAttachments. Enables the assignments of ImageAttachments.
""" """
images = GenericRelation( images = GenericRelation(
to='extras.ImageAttachment' to='extras.ImageAttachment',
content_type_field='object_type',
object_id_field='object_id'
) )
class Meta: class Meta:

View File

@ -91,7 +91,7 @@ class ContactImportForm(NetBoxModelImportForm):
class ContactAssignmentImportForm(NetBoxModelImportForm): class ContactAssignmentImportForm(NetBoxModelImportForm):
content_type = CSVContentTypeField( object_type = CSVContentTypeField(
queryset=ContentType.objects.all(), queryset=ContentType.objects.all(),
help_text=_("One or more assigned object types") help_text=_("One or more assigned object types")
) )
@ -108,4 +108,4 @@ class ContactAssignmentImportForm(NetBoxModelImportForm):
class Meta: class Meta:
model = ContactAssignment model = ContactAssignment
fields = ('content_type', 'object_id', 'contact', 'priority', 'role') fields = ('object_type', 'object_id', 'contact', 'priority', 'role')