Skip to content

Instantly share code, notes, and snippets.

@Cguilliman
Last active May 8, 2018 10:40
Show Gist options
  • Save Cguilliman/06d150b6315efda43d20c7a9baa7a493 to your computer and use it in GitHub Desktop.
Save Cguilliman/06d150b6315efda43d20c7a9baa7a493 to your computer and use it in GitHub Desktop.
models for dynamic attributes
# models
from django import models
from django.utils.translation import ugettext_lazy as _
class RowAttribute(models.Model):
"""Product/look row attribute model."""
product = models.ForeignKey(
'ModelWithAttribute', verbose_name=_('Product'),
on_delete=models.CASCADE, null=True,
blank=True, related_name='row_attribute'
)
attribute = models.ForeignKey(
'Attribute', on_delete=models.CASCADE,
verbose_name=_('Attribute'),
related_name='row_attribute'
)
value = models.ForeignKey(
'AttributeValue', on_delete=models.CASCADE,
verbose_name=_('Value'),
related_name='row_attribute',
null=True, blank=True
)
class Meta:
verbose_name = _('Row attribute')
verbose_name_plural = _('Row attributes')
def __str__(self) -> str:
return self.attribute.name
class Attribute(models.Model):
"""Attribute model"""
name = models.CharField(verbose_name=_('Name'), max_length=255)
# some more relatied stuff
class Meta:
verbose_name = _('Attribute')
verbose_name_plural = _('Attributes')
def __str__(self) -> str:
return self.name
class AttributeValue(models.Model):
"""Attribute variation model"""
value = models.CharField(verbose_name=_('Attribute value'), max_length=255)
attr = models.ForeignKey(
Attribute, verbose_name=_('Attribute'),
on_delete=models.CASCADE,
related_name='value'
)
class Meta:
verbose_name = _('Attribute variation')
verbose_name_plural = _('Attribute variations')
def __str__(self) -> str:
return f'{self.attr.name} - {self.value}'
# admin
class RowAttributeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RowAttributeForm, self).__init__(*args, **kwargs)
# fix value when instance already exists
if self.initial:
self.fields['attribute'].disabled = True
self.fields['value'].queryset = AttributeValue.objects.filter(
attribute=self.initial.attribute
)
class RowAttributeInline(admin.StackedInline):
form = RowAttributeForm
model = RowAttribute
exotra = 0
def get_fields(self, request, obj=None):
fields = super().get_fields(request, obj)
if not obj:
fields.remove('value')
return fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment