Django rest m2m nested serializer create/update nested objects - django

I have a model Scenario:
class Scenario(models.Model):
stakeholder = models.ForeignKey(User, related_name='scenarios', blank=True,)
tasks = models.ManyToManyField(Task, blank=True)
Task objects are already created and from my fronted I create a scenario by adding a few of the existing tasks to it.
Serializer:
class ScenarioSerializer(serializers.ModelSerializer):
tasks = TaskSerializer(many=True, required=False)
class Meta:
model = Scenario
fields = '__all__'
def create(self, validated_data):
tasks = validated_data.pop('tasks')
scenario = Scenario.objects.create(**validated_data)
for task in tasks:
Task.objects.update(scenario=scenario, **task)
return scenario
Without create() method it throws error:
AssertionError: The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `scenarios.serializers.ScenarioSerializer`, or set `read_only=True` on nested serializer fields.
When I added this method, error was gone but it threw:
FieldError: Cannot update model field <ManyToManyRel: scenarios.scenario> (only non-relations and foreign keys permitted)
What am I doing wrong? I do not want to create new tasks, just create a new scenario and attach existing tasks to it.
Update: Task model:
class Task(models.Model):
stakeholder = models.ForeignKey(User, related_name='tasks', blank=True, )
project = models.ForeignKey(Project, related_name='project_tasks' )
title = models.CharField(max_length=50, blank=True, null = True, )
OFTEN_CHOICES = (
('DS', 'Daily several times'),
('DO', 'Daily once'),
('WO', 'Weekly once'),
('MO', 'Monthly once'),
('YO', 'Yearly once'),
)
how_often = models.CharField(blank=True, null = True, choices=OFTEN_CHOICES, max_length=2, )
IMPORTANCE_CHOICES = (
('EI', 'Extremely important'),
('RI', 'Rather important'),
('LI', 'Less important'),
)
how_important_task = models.CharField(blank=True, null = True, choices=IMPORTANCE_CHOICES, max_length=2, )
role = models.CharField(max_length=20, blank=True, null = True, )
why_perform_task = models.CharField(max_length=150, blank=True, null = True, )
why_important_task = models.CharField(max_length=150, blank=True, null = True, )
sequence_of_actions = models.CharField(max_length=500, blank=True, null = True, )
tools_used = models.CharField(max_length=150, blank=True, null = True, )
special_training_required = models.NullBooleanField(blank=True, null = True, default=False, )
what_training_required = models.CharField(max_length=150, blank=True, null = True, )
what_can_go_wrong = models.CharField(max_length=150, blank=True, null = True, )
effects_of_task = models.CharField(max_length=150, blank=True, null = True, )
special_vocabulary_used = models.CharField(max_length=150, blank=True, null = True, )
people_involved = models.CharField(max_length=150, blank=True, null = True, )
any_improvements = models.CharField(max_length=150, blank=True, null = True, )
how_important_improvement = models.CharField(blank=True, null = True, choices=IMPORTANCE_CHOICES, max_length=2, )
benefits_of_improvement = models.CharField(max_length=150, blank=True, null = True, )
sample request data:
{"tasks":[{"id":7,"title":"Seven","how_often":"","how_important_task":"","role":"","why_perform_task":"","why_important_task":null,"sequence_of_actions":"","tools_used":"","special_training_required":null,"what_training_required":"","what_can_go_wrong":"","effects_of_task":"","special_vocabulary_used":"","people_involved":"","any_improvements":"","how_important_improvement":"","benefits_of_improvement":"","stakeholder":2,"project":1}]}

you done first part and now need add method update here docs:
for example
class ScenarioSerializer(serializers.ModelSerializer):
tasks = TaskSerializer(many=True, required=False)
class Meta:
model = Scenario
fields = '__all__'
def create(self, validated_data):
tasks = validated_data.pop('tasks', [])
instance = Scenario.objects.create(**validated_data)
for task_data in tasks:
task = Task.objects.get(pk=task_data.get('id'))
instance.tasks.add(task)
return instance
def update(self, instance, validated_data):
tasks = validated_data.pop('tasks', [])
instance = super().update(instance, validated_data)
for task_data in tasks:
task = Task.objects.get(pk=task_data.get('id'))
instance.tasks.add(task)
return instance

This problem was solved by following the steps in this post https://lynxbee.com/solved-the-create-method-does-not-support-writable-nested-fields-by-default/.
pip install drf_writable_nested
from drf_writable_nested import WritableNestedModelSerializer
class YourSerializer(WritableNestedModelSerializer, serializers.ModelSerializer):
pass

Related

django check-contraint boolean expression [postgresql]

So I have a model like this
class Role(BaseModel):
class Meta:
verbose_name = 'role'
verbose_name_plural = 'roles'
ordering = ['position', 'cluster']
required_db_features = {
'supports_deferrable_unique_constraints',
}
constraints = [
models.UniqueConstraint(
fields=['position', 'cluster'],
name='deferrable_unique_role_position',
deferrable=models.Deferrable.DEFERRED
),
models.CheckConstraint(
name='default_role_check',
check=models.Q(
is_default=True,
position=1,
color='#969696',
name='#everyone'
)
)
]
permission_flags = [
'READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS', 'MANAGE_ROLES',
'MANAGE_CLUSTER', 'MANAGE_DATASHEETS', 'MANAGE_FIELDS', 'MANAGE_CONSTRAINTS',
'KICK_MEMBERS', 'MANAGE_MEMBERS',
]
default_perm_flags = ['READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS']
def __str__(self):
return self.name
objects = managers.RolesManager()
positions = managers.PositionalManager()
permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True)
position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True)
name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role')
color = ColorField(db_index=True, default='#969696')
is_default = models.BooleanField(default=False, db_index=True)
cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False)
Basically I want to enforce a check constraint on this model such that
when the model has the is_default field set to True,
the name must always be #everyone
the color must always be #969696
the position must always be 1.
I tried to implement the same, however my current implementation doesn't work.
While using serializers, I can edit the default role's name, and no exceptions are raised.
I am using postgresql at the backend.
Can someone please help me?
thanks in advance!
Adding an is_default=False case get you closer to your conditions.
I tested with Django==3.1.4 and the OR method resulted in this constraint:
"default_role_check" CHECK (color::text = '#969696'::text AND is_default AND name::text = '#everyone'::text AND "position" = 1 OR NOT is_default)
Constraint example:
class Role(BaseModel):
class Meta:
verbose_name = 'role'
verbose_name_plural = 'roles'
ordering = ['position', 'cluster']
required_db_features = {
'supports_deferrable_unique_constraints',
}
constraints = [
models.UniqueConstraint(
fields=['position', 'cluster'],
name='deferrable_unique_role_position',
deferrable=models.Deferrable.DEFERRED
),
models.CheckConstraint(
name='default_role_check',
check=(models.Q(
is_default=True,
position=1,
color='#969696',
name='#everyone'
) |
models.Q(
is_default=False,
)
)
)
]
permission_flags = [
'READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS', 'MANAGE_ROLES',
'MANAGE_CLUSTER', 'MANAGE_DATASHEETS', 'MANAGE_FIELDS', 'MANAGE_CONSTRAINTS',
'KICK_MEMBERS', 'MANAGE_MEMBERS',
]
default_perm_flags = ['READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS']
def __str__(self):
return self.name
objects = managers.RolesManager()
positions = managers.PositionalManager()
permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True)
position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True)
name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role')
color = ColorField(db_index=True, default='#969696')
is_default = models.BooleanField(default=False, db_index=True)
cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False)

How could I change a Boolean field to show a value like Up = true or Down = False in a serialized field in Django

I have a serialized data set in Django Rest Framework to be consumed, but I have a question that I want to solve, there is a field that is Boolean, and clearly when I serialize it shows two values: true or false, the question is that I do not want show these values, I want to show UP = True, DOWN = False
These fields in question are: status and ospf
My Model
class Interfaces(models.Model):
id_interface = models.PositiveIntegerField(primary_key=True)
id_EquipoOrigen = models.ForeignKey(Equipos, on_delete=models.DO_NOTHING, related_name='equipo_origen')
id_PuertoOrigen = models.ForeignKey(Puertos, on_delete=models.DO_NOTHING, related_name='puerto_origen', null=True, blank=True)
estatus = models.BooleanField(default=False)
etiqueta_prtg = models.CharField(max_length=80, null=True, blank=True)
grupo = models.PositiveSmallIntegerField(default=0, blank=True)
if_index = models.PositiveIntegerField(default=0, blank=True)
bw = models.PositiveSmallIntegerField(default=0, blank=True)
bw_al = models.PositiveSmallIntegerField(default=0, blank=True)
id_prtg = models.PositiveSmallIntegerField(default=0, blank=True)
ospf = models.BooleanField(default=False)
description = models.CharField(max_length=200, null=True, blank=True)
id_EquipoDestino = models.ForeignKey(Equipos, on_delete=models.DO_NOTHING, related_name='equipo_destino')
id_PuertoDestino = models.ForeignKey(Puertos, on_delete=models.DO_NOTHING, related_name='puerto_destino')
ultima_actualizacion = models.DateTimeField(auto_now=True)
My Serializers Model Interfaces
class InterfaceSerializer(serializers.ModelSerializer):
EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True)
PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True)
LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True)
CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True)
EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True)
PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True)
LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True)
CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True)
Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True)
class Meta:
model=Interfaces
fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',)
class InterfacesViewSet(viewsets.ModelViewSet):
queryset = Interfaces.objects.all()
serializer_class = InterfaceSerializer
pagination_class = PostPageNumberPagination
filter_class = InterfacesFilter
You can use SerializerMethodField for that
class InterfaceSerializer(serializers.ModelSerializer):
estatus = serializers.SerializerMethodField(method_name='conversion_bool')
EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True)
PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True)
LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True)
CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True)
EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True)
PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True)
LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True)
CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True)
Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True)
class Meta:
model=Interfaces
fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen',
'LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo',
'if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino',
'EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino',
'ultima_actualizacion',)
def conversion_bool(self, instance):
if instance.estatus == True:
return "Up"
else:
return "Down"
Like this you can do for any other field.
The quick and read-only way is to use a SerializerMethodField.
The most complete way which supports read / write is to create a custom SerializerField. Override to_representation and to_internal_value to handle the translation between boolean and your custom representation.

how to limit_choices_to self field id in django model

how use limit_choices_to in django
class Category(models.Model):
"""
商品类别
"""
CATEGORY_TYPE = (
(1, "一级类目"),
(2, "二级类目"),
(3, "三级类目"),
)
def limit_category_type_choice(self):
obj = Category.objects.get(category_type=self.category_type)
field_object = Category._meta.get_field('category_type')
field_value = field_object.value_from_object(obj)
return {'category_type__lte': field_value}
category_id = models.AutoField(primary_key=True, verbose_name='category_id')
category_title = models.CharField(default='', max_length=50, verbose_name='目录标题', help_text='目录标题')
category_name = models.ForeignKey(LinkDesignate,blank=True, null=True, to_field='link_des_text_id', related_name='category', on_delete=models.CASCADE)
category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别")
parent_category = models.ForeignKey("self", limit_choices_to=self.limit_category_type_choice, null=True, blank=True, verbose_name="父类目级别", help_text="父目录",
related_name="sub_cat", on_delete=models.CASCADE)
class Meta:
verbose_name = "产品目录"
verbose_name_plural = verbose_name
i know this
limit_choices_to=self.limit_category_type_choice,
this is wrong , because name 'self' is not defined
how can to use the function limit_category_type_choice
the document is:
def limit_pub_date_choices():
return {'pub_date__lte': datetime.date.utcnow()}
limit_choices_to = limit_pub_date_choices
how can i change my Function limit_category_type_choice without self
but can use the self instance
Put the def out of the class ;-)
This was my solution, it is similar.
It limits the films which can be choosen for an event.
Films with status '2' in class Film over ForeignKey OR
over reverse ForeignKey: Films with an Event with date in the future
the model:
def limit_film_choices():
date = str(datetime.datetime.now())
result = Q( status = '2') | Q( event_film__date__gte = date)
return result
class Film(models.Model):
STATUS_COICES = [
('1' , 'a'),
('2' , 'b'),
]
status = models.CharField( max_length=16, choices=STATUS_COICES, default='1')
class Event(models.Model):
film = models.ForeignKey('filme.Film', on_delete=models.CASCADE, related_query_name='event_film',
related_name='event_film', blank = True, null=True, limit_choices_to = limit_film_choices)
date = models.DateTimeField(auto_now=False, null=True)

How do I make this serializer display correctly?

Django is giving me this error. The solution I've tried does not seem to work. It is asking me to make this an instance of Medication...Am I not already doing that? I'm trying to have two serializers cat and medication under the one careLogSerializer. Is that even possible? How can I best solve this error?
builtins.ValueError
ValueError: Cannot assign "OrderedDict([('name', 'carelog3'), ('duration', 'short'), ('frequency', '4')])": "CareLog.medication" must be a "Medication" instance.
Here is my serializer....
class CareLogSerializer(serializers.HyperlinkedModelSerializer):
cat = CatSerializer()
medication = MedicationSerializer()
# cat = CatSerializer(read_only=True) this allows put BUT TURNS OFF POST
class Meta:
model = CareLog
fields = (
'cat',
'slug',
'foster_manager',
'weight_unit_measure',
'weight_before_food',
'food_unit_measure',
'amount_of_food_taken',
'food_type',
'weight_after_food',
'stimulated',
'medication',
'medication_dosage_given',
'medication_dosage_unit',
'notes',
'created',
'photo',
)
extra_kwargs = {
'foster_manager': {
'read_only': True,
'required': False,
'lookup_field': 'id',
},
'medication': {
'read_only': True,
'required': False,
'lookup_field': 'slug',
},
'cat': {
'read_only': True,
'required': False,
'lookup_field': 'slug',
},
}
#staticmethod
def create(validated_data):
cat_data = validated_data.pop('cat')
cat_obj = Cat.objects.get(**cat_data)
return CareLog.objects.create(cat=cat_obj, **validated_data)
#staticmethod
def update(instance, validated_data):
instance.weight_unit_measure = validated_data['weight_unit_measure']
instance.weight_before_food = validated_data['weight_before_food']
instance.food_unit_measure = validated_data['food_unit_measure']
instance.amount_of_food_taken = validated_data['amount_of_food_taken']
instance.food_type = validated_data['food_type']
instance.weight_after_food = validated_data['weight_after_food']
instance.stimulated = validated_data['stimulated']
instance.stimulation_type = validated_data['stimulation_type']
instance.notes = validated_data['notes']
instance.save()
Here is my model
class CareLog(models.Model):
WEIGHT_MEASURE_CHOICES = (
('OZ', '(oz) Ounces'),
('LB', '(lb) Pounds'),
('G', '(G) Grams')
)
OUNCES = 'OZ'
POUNDS = 'LB'
GRAMS = 'G'
VOLUME_MEASURE_CHOICES = (
('ML', '(ml) Milliliters'),
('CC', '(cc) Cubic Centimeters'),
('OZ', '(oz) Ounces'),
('G', '(G) Grams')
)
MILLILITERS = 'ML'
CUBIC_CENTIMETERS = 'CC'
FOOD_TYPE_CHOICES = (
('MN', 'Mom (Nursing)'),
('BO', 'Bottle'),
('BS', 'Bottle / Syringe'),
('SG', 'Syringe Gruel'),
('GG', 'Syringe Gruel / Gruel'),
('G', 'Gruel')
)
BOTTLE = 'BO'
BOTTLE_SYRINGE = 'BS'
SYRINGE_GRUEL = 'SG'
SYRINGE_GRUEL_GRUEL = 'GG'
GRUEL = 'G'
STIMULATION_CHOICES = (
('UR', 'Urine'),
('FE', 'Feces'),
('UF', 'Urine / Feces'),
)
URINE = 'UR'
FECES = 'FE'
URINE_FECES = 'UF'
cat = models.ForeignKey(Cat)
slug = AutoSlugField(max_length=255, unique=True, blank=True, null=True)
foster_manager = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
weight_unit_measure = models.CharField(max_length=2, choices=WEIGHT_MEASURE_CHOICES, default=GRAMS)
weight_before_food = models.IntegerField(blank=True, null=True)
food_unit_measure = models.CharField(max_length=2, choices=WEIGHT_MEASURE_CHOICES, default=GRAMS)
amount_of_food_taken = models.IntegerField(blank=True, null=True)
food_type = models.CharField(max_length=2, choices=FOOD_TYPE_CHOICES, blank=True, null=True)
weight_after_food = models.IntegerField(blank=True, null=True)
stimulated = models.BooleanField(default=False)
stimulation_type = models.CharField(max_length=2, choices=STIMULATION_CHOICES, blank=True, null=True)
medication = models.ForeignKey(Medication, blank=True, null=True)
medication_dosage_given = models.FloatField(blank=True, null=True)
medication_dosage_unit = models.CharField(max_length=2, choices=VOLUME_MEASURE_CHOICES, blank=True, null=True,
help_text="If left blank this will default to "
"the default unit for the medication.")
notes = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
photo = models.FileField(upload_to="kitty_photos", blank=True, null=True)
def save(self, *args, **kwargs):
# Update Cat's weight if 'Weight After Food' is updated
if self.weight_after_food:
self.cat.weight = self.weight_after_food
self.cat.save()
# Get all previous cat feedings
feedings = CareLog.objects.filter(cat=self.cat).order_by('-id')
if feedings:
# if the list of cat feedings contains the current, get rid of current from the list
if feedings[0] == self:
feedings = feedings[1:]
# TODO You broke it you fix it:
# If the feeding is a weight loss log it as the first/second/third
if self.weight_after_food < feedings[0].weight_after_food:
if self.cat.first_weight_loss:
self.cat.second_weight_loss = True
elif self.cat.second_weight_loss:
self.cat.third_weight_loss = True
elif self.cat.third_weight_loss:
self.cat.many_weight_losses = True
elif not self.cat.first_weight_loss:
self.cat.first_weight_loss = True
# Save Cat Object
self.cat.save()
if self.medication and not self.medication_dosage_unit:
self.medication_dosage_unit = self.medication.dosage_unit
super(CareLog, self).save(*args, **kwargs)
def __str__(self):
return "{cat}: {timestamp}".format(cat=self.cat.name, timestamp=self.created)
In your create method you need to do for medication same operation as for cat. Create object first and assign it to CareLog:
#staticmethod
def create(validated_data):
cat_data = validated_data.pop('cat')
cat_obj = Cat.objects.get(**cat_data)
med_data = validated_data.pop('medication')
med_obj = Medication.objects.create(**med_data)
return CareLog.objects.create(cat=cat_obj, medication=med_obj, **validated_data)
Otherwise Django trying to set as foreignkey's value dict object and raise the error.

django m2m model not syncing

When I run syncdb on my new m2m model I get the error:
Error: One or more models did not validate:
services.service: 'categories' specifies an m2m relation through model Service_Category, which has not been installed
I tried using the example listed on
https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
and when I synced that it worked fine. SO I am not getting something right with my model below. Not really sure why my model isnt working and if its a simple typo or something else. NOTE: The models worked fine using a simple m2m relationship but it doesnt like it this way. Thanks
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255, blank = True, null = True,
help_text='Content for description meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
class Meta:
#app_label = ''
db_table = 'categories'
ordering = ['created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_category', (), {'category_slug': self.slug})
class Service(models.Model):
name = models.CharField(max_length=255, unique = True)
slug = models.SlugField(max_length=255, unique = True,
help_text = 'Unique value for product page URL, created from name.')
old_price = models.DecimalField(max_digits=9, decimal_places=2,
blank = True, null = True, default = 0.0)
image = models.CharField(max_length=50, blank = True)
is_active = models.BooleanField(default = True)
is_bestseller = models.BooleanField(default = False)
is_featured = models.BooleanField(default = False)
description = models.TextField()
bullet1 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet2 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet3 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet4 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
bullet5 = models.CharField(max_length=255, blank = True, null = True,
help_text = 'Option Bullet for description')
micro_current = models.BooleanField(default = False)
meta_keywords = models.CharField(max_length = 255,blank = True, null = True,
help_text = 'Comma Delimited Set of SEO keywords for meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
categories = models.ManyToManyField(Category, through='Service_Category')
class Meta:
#app_label = ''
db_table = 'services'
ordering = ['created_at']
def __unicode__(self):
return self.name
class Service_Category:
category = models.ForeignKey(Category)
service = models.ForeignKey(Service)
micro_current = models.BooleanField(default = False)
class Meta:
#app_label = ''
db_table = 'service_categories'
services.service: 'categories' specifies an m2m relation through model Service_Category, which has not been installed
You missed to define your intermediate model correctly
class Service_Category(models.Model):
category = models.ForeignKey(Category)
service = models.ForeignKey(Service)
micro_current = models.BooleanField(default = False)
class Meta:
#app_label = ''
db_table = 'service_categories'
We have to inherit each of our model which we define from models.Model class.
Rest everything seems to be fine.
Service_Category needs to inherit from models.Model
i.e, class Service_Category(models.Model):