Nested Serializers with multiple tables not working - django

I have the below tables in models.py.
class ProductLine(models.Model):
availability = models.CharField(max_length=20, blank=True, null=True)
series = models.CharField(max_length=20, blank=True, null=True)
model = models.CharField(max_length=20, blank=True, null=True)
class Meta:
db_table = "product_line"
class DriveType(models.Model):
drive_name = models.CharField(max_length=20, blank=True, null=True)
product_line = models.ForeignKey(ProductLine, related_name="drive_type")
class Requirements(models.Model):
performance_unit = models.CharField(max_length=100, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)
class Meta:
db_table = "requirements"
class WorkloadType(models.Model):
workload_type_options = models.CharField(max_length=50, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)
class Meta:
db_table = "workload_type"
I have below serializers:
class WorkloadTypeSerializer(serializers.ModelSerializer):
class Meta:
model = WorkloadType
fields = "__all__"
class RequirementsSerializer(serializers.ModelSerializer):
class Meta:
model = Requirements
fields = "__all__"
class DriveTypeSerializer(serializers.ModelSerializer):
requirements = RequirementsSerializer(many = False, read_only = True)
workload_type = WorkloadTypeSerializer(many=False,read_only=True)
class Meta:
model = DriveType
fields = (
"drive_name", "available_drive_type", "capacity", "raid_type", "raid_size", "workload", "workload_percentage",
"raid_groups", "compression", "compression_value","requirements","workload_type")
class ProductLineSerializer(serializers.ModelSerializer):
drive_type = DriveTypeSerializer(many=True, read_only=True)
class Meta:
model = ProductLine
fields = ('availability','series','model','drive_type')
In my views I have this:
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
def get_queryset(self):
return ProductLine.objects.filter(id=self.kwargs.get("pk"))
serializer_class = ProductLineSerializer
I am getting output as below :
{
"availability": "Current",
"series": "3000",
"model": "2000",
"drive_type": [
{
"drive_name": "drive1",
"requirements": {
"drive_type": 2,
"performance_unit": "by_iops",
}
}
]
}
Why I am not able to see WorkLoadType tables data in json where as I am able to see Requirements data . I don't even see the field in json. Nested serializers only support a single relation tables

Answering my own question. Have to use related_name in the models for reverse relationship.
class Requirements(models.Model):
performance_unit = models.CharField(max_length=100, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=requirements)
class Meta:
db_table = "requirements"
class WorkloadType(models.Model):
workload_type_options = models.CharField(max_length=50, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=workload_type)

Related

django-import-export how to deal with the import_id_fields is unique_together key?

the parentmodel is
class Work(models.Model):
po = models.ForeignKey(Po, verbose_name="合同号", on_delete=models.CASCADE)
remark = models.CharField(max_length=100, verbose_name="备注说明")
create_time=models.DateField(verbose_name="日期")
class Meta:
verbose_name = "工作清单"
verbose_name_plural = verbose_name
unique_together=("po","remark")
def __str__(self):
return self.remark
and the children model is
class Acceptance(models.Model):
work = models.ForeignKey(Work, on_delete=models.CASCADE, verbose_name="工作清单")
detail=models.ForeignKey(Detail,on_delete=models.CASCADE,verbose_name="验收物品")
accecpt_time = models.DateField(verbose_name="验收日期")
num = models.IntegerField(verbose_name="验收数量", validators=[MinValueValidator(1)])
person = models.CharField(max_length=100, verbose_name="验收人员")
class Meta:
verbose_name = "验收清单"
verbose_name_plural = verbose_name
unique_together=("accecpt_time","work")
I want to ask about how to defind the Acceptance Resource when the work foreign_key is unique_together key?
my test code is
class AcceptanceSource(resources.ModelResource):
work = fields.Field(attribute="work", widget=ForeignKeyWidget(Work, 'remark'), column_name="工作清单")
detail = fields.Field(attribute="detail", widget=ForeignKeyWidget(Detail, "name"), column_name="物料清单")
po = fields.Field(attribute="work__po", column_name="合同号", widget=ForeignKeyWidget(Po, "po_num"))
num = fields.Field(attribute="num", column_name="验收数量")
accecpt_time = fields.Field(attribute="accecpt_time", column_name="验收时间")
person = fields.Field(attribute="person", column_name="验收人员")
but it get error like this:
行号: 1 - get() returned more than one Work -- it returned 2!

How to make a one to many relationship in Django/Mysql?

I am trying to understand how to make a one to many relationship in Django/Mysql?
Here is models.py (code below)
class Flora2Estado(models.Model):
estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True)
especie = models.ForeignKey('Listaflor', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie'),)
class Listaflor(models.Model):
especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True)
familia = models.ForeignKey(Familia, models.DO_NOTHING, blank=True, null=True)
nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True) # Field renamed because of name conflict.
class Meta:
managed = False
db_table = 'listaflor'
class Estados(models.Model):
estado_id = models.AutoField(primary_key=True)
estado_nome = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'estados
I think that what you want to do is a Many2Many relation between Listaflor and Estados through another class called Flora2Estado. Django M2M relation
class Estados(models.Model):
estado_id = models.AutoField(primary_key=True)
estado_nome = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'estados'
class Listaflor(models.Model):
especie_id = models.AutoField(primary_key=True)
nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True)
estados = models.ManyToManyField(Estados, through='Flora2Estado')
class Meta:
managed = False
db_table = 'listaflor'
class Flora2Estado(models.Model):
estado = models.ForeignKey(Estados, on_delete=models.DO_NOTHING)
especie = models.ForeignKey(Listaflor, on_delete=models.DO_NOTHING)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie'),)

DRF post request multiple inner serializers

i have three models named Smoker,Switch,Survey i have smoker as foreign key in Switch model and switch as foreign key in Survey model
class Smoker(models.Model):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
mobile = models.IntegerField(null=True, blank=True)
gender = models.BooleanField(blank=True, null=True)
age = models.ForeignKey(Age,models.DO_NOTHING,blank=True, null=True)
occupation = models.ForeignKey(Occupation, models.DO_NOTHING, blank=True, null=True)
class Switch(models.Model):
time = models.TimeField(blank=True, null=True)
count_outers = models.IntegerField(blank=True, null=True)
count_packs = models.IntegerField(blank=True, null=True)
smoker = models.ForeignKey(Smoker, models.DO_NOTHING, blank=True, null=True)
new_brand = models.ForeignKey(NewBrand, models.DO_NOTHING, blank=True, null=True)
new_sku = models.ForeignKey(NewSku, models.DO_NOTHING, blank=True, null=True)
# def __str__(self):
# return self.time.strftime("%H:%M")
class Survey(models.Model):
user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True)
date = models.DateField(null=True, blank=True)
bool_switch = models.BooleanField(null=True, blank=True)
reason = models.ForeignKey(Reason, models.DO_NOTHING, null=True, blank=True)
shift = models.ForeignKey(ShiftingTime, models.DO_NOTHING, null=True, blank=True)
current_brand = models.ForeignKey(CurrentBrand, models.DO_NOTHING, null=True, blank=True)
current_sku = models.ForeignKey(CurrentSku, models.DO_NOTHING, null=True, blank=True)
pos = models.ForeignKey(Pos, models.DO_NOTHING, null=True, blank=True)
switch = models.ForeignKey(Switch, models.DO_NOTHING, null=True, blank=True)
and here i have my serializers:
class SmokerSerializer(serializers.ModelSerializer):
class Meta:
model = Smoker
fields = '__all__'
class SwitchSerializer(serializers.ModelSerializer):
smoker = SmokerSerializer()
class Meta:
model = Switch
fields = '__all__'
def create(self, validated_data):
smoker_data = validated_data.pop('smoker', None)
if smoker_data:
smoker = Smoker.objects.create(**smoker_data)
validated_data['smoker'] = smoker
return Switch.objects.create(**validated_data)
class SurveySerializer(serializers.ModelSerializer):
switch = SwitchSerializer()
class Meta:
model = Survey
fields = '__all__'
def create(self, validated_data):
switch_data = validated_data.pop('switch', None)
if switch_data:
switch = Switch.objects.create(**switch_data)
validated_data['switch'] = switch
return Survey.objects.create(**validated_data)
and i make a generic for for Creating and listing all the survey
class SurveyCreateAPIView(generics.ListCreateAPIView):
def get_queryset(self):
return Survey.objects.all()
serializer_class = SurveySerializer
for each displayed survey i have to display switch data related to it and inside the switch object i need to display the smoker object inside it so each survey object must look like this
{
"id": 11,
"switch": {
"id": 12,
"smoker": {
"firstname":"sami",
"lastname:"hamad",
"mobile":"7983832",
"gender":"0",
"age":"2",
"occupation":"2"
},
"time": null,
"count_outers": 5,
"count_packs": 7,
"new_brand": 2,
"new_sku": 2
},
"date": "2018-12-08",
"bool_switch": true,
"user": 7,
"reason": 3,
"shift": 2,
"current_brand": 6,
"current_sku": 4,
"pos": 2
},
but when i make a POST request it is giving me this error
ValueError at /api/v2/surveysync/ Cannot assign
"OrderedDict([('first_name', 'aline'), ('last_name', 'youssef'),
('mobile', 7488483), ('gender', False), ('age', ),
('occupation', )])": "Switch.smoker" must be
a "Smoker" instance.
so please help and thank you so much!
You're going along the right path but you're saving the switch objects manually instead of allowing the SwitchSerializer do it for you. Same thing with create method in switch serializer. It should be this way:
class SmokerSerializer(serializers.ModelSerializer):
class Meta:
model = Smoker
fields = '__all__'
class SwitchSerializer(serializers.ModelSerializer):
smoker = SmokerSerializer()
class Meta:
model = Switch
fields = '__all__'
def create(self, validated_data):
smoker_data = validated_data.pop('smoker', None)
if smoker_data:
serializer = SmokerSerializer(data=smoker_data, context=self.context)
if serializer.is_valid():
validated_data['smoker'] = serializer.save()
return super().create(validated_data)
class SurveySerializer(serializers.ModelSerializer):
switch = SwitchSerializer()
class Meta:
model = Survey
fields = '__all__'
def create(self, validated_data):
switch_data = validated_data.pop('switch', None)
if switch_data:
serializer = SwitchSerializer(data=switch_data, context=self.context)
if serializer.is_valid():
validated_data['switch'] = serializer.save()
return super().create(validated_data)
In SwitchSerializer you defined the create function as a method of the inner Meta class and not as a member of SwitchSerializer class. Try this
class SwitchSerializer(serializers.ModelSerializer):
smoker = SmokerSerializer()
class Meta:
model = Switch
fields = '__all__'
def create(self, validated_data):
smoker_data = validated_data.pop('smoker', None)
if smoker_data:
smoker = Smoker.objects.create(**smoker_data)
validated_data['smoker'] = smoker
return Switch.objects.create(**validated_data)

Nested serializers in drf throws error with one to one field

My input json is :
{
"availability": "Current",
"drive_type": [{
"drive_name": "drive1",
"requirements": {
"performance_unit": "by_iops",
}
}]
}
I am getting error Cannot assign "
OrderedDict([('performance_unit', 'Basic')])":
"DriveType.requirements" must be a "Requirements" instance
.I am not able to figure it out to map in create method for one to one fields in tables
Below are my models.py
class ProductLine(models.Model):
availability = models.CharField(max_length=20, blank=True, null=True)
class Meta:
db_table = "product_line"
class DriveType(models.Model):
drive_name = models.CharField(max_length=20, blank=True, null=True)
product_line = models.ForeignKey(ProductLine, related_name="drive_type")
class Meta:
db_table = "drive_type"
class Requirements(models.Model):
performance_unit = models.CharField(max_length=100, blank=True, null=True)
drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name="requirements")
class Meta:
db_table = "requirements"
Serializers.py :
class DriveTypeSerializer(serializers.ModelSerializer):
requirements = RequirementsSerializer(many = True)
class Meta:
model = DriveType
fields = (
"drive_name","workload_type")
class ProductLineSerializer(serializers.ModelSerializer):
drive_type = DriveTypeSerializer(many=True)
class Meta:
model = ProductLine
fields = ('availability', "drive_type")
def create(self, validated_data):
print("validate_data",validated_data)
drive_type_data = validated_data.pop("drive_type")
product_line = ProductLine.objects.create(**validated_data)
for drive_data in drive_type_data:
drive_type = DriveType.objects.create(product_line=product_line, **drive_data)
return product_line
You have one to one relationship of DriveType and Requirements
So remove many = True from DriveTypeSerializer for RequirementsSerializer
class DriveTypeSerializer(serializers.ModelSerializer):
requirements = RequirementsSerializer()
class Meta:
model = DriveType
fields = ("drive_name","workload_type")
Your input json has only one object of requirements not a list

How to serialize list of strings with Django Rest Framework

I have serializer in Django rest framework as follows:
class StateSerializer(serializers.ModelSerializer):
kilometers = Field(source='mileage')
pictures = StatePictureSerializer(many=True, read_only=True)
class Meta:
model = Inspection # Options
fields = ('kilometers', 'inspection_date', 'pictures')
And StatePictureSerializer is as follows:
class StatePictureSerializer(serializers.ModelSerializer):
blob_url = Field(source='public_url')
class Meta:
model = Inspection_Picture
fields = ('blob_url', )
As result I get something as follows:
{
"kilometers": 64431,
"inspection_date": null,
"pictures": [
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"},
{"blob_url": "path/to/photo"}
]
}
Thus, pictures is an array of objects.
What I want is an array of strings, for example:
"pictures": ["path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo"]
Any idea how to do that?
EDIT
Inspection model is as follows:
class Inspection(models.Model):
customerReference = models.CharField(max_length=50, blank=True, null=True)
extraReference = models.CharField(max_length=50, blank=True, null=True)
itemReference = models.IntegerField(blank=True, null=True)
vehicle = models.ForeignKey(to=Vehicle)
mileage = models.IntegerField()
timeStamp = models.DateTimeField(auto_now_add=True)
inspection_date = models.DateTimeField(null=True)
features = models.ManyToManyField(to=Feature)
pictures = models.ManyToManyField(to=Images, through="Inspection_Picture")
damages = models.ManyToManyField(to=Damage)
parts = models.ManyToManyField(to=Part)
checks = models.ManyToManyField(to=CheckType, through=Inspection_Check)
featuresFlat = models.ManyToManyField(to=FeatureFlat, through=Inspection_FeatureFlat)
And Images model is as follows:
class Images(models.Model):
"""Model for storing uploaded photos"""
filename = models.CharField(max_length=255)
extension = models.CharField(max_length=40)
key_data = models.CharField(max_length=90, unique=True, blank=True, null=True)
upload_date = models.DateTimeField(auto_now_add=True)
upload_identification = models.CharField(max_length=50, blank=True, null=True)
url = models.CharField(max_length=1024, blank=True, null=True)
stored = models.BooleanField(default=False)
thumbnailed = models.BooleanField(default=False)
thumbnailed_treated = models.BooleanField(default=False)
protected = models.BooleanField(default=False)
source = models.CharField(max_length=50, blank=True, null=True)
#property
def key_generate(self):
"""returns a string based unique key with length 80 chars"""
while 1:
key = str(random.getrandbits(256))
try:
Images.objects.get(key=key)
except:
return key
def __unicode__(self):
return self.upload_identification
def public_url(self):
return settings.AZURE_URL_FULL + self.url
I think in your case SerializerMethodField would be a right choice as follows. There may be <field_name> mismatch in the code below. Please make it working according your model. I assume the field names based on your serializer above.
class StateSerializer(serializers.ModelSerializer):
kilometers = Field(source='mileage')
pictures = serializers.SerializerMethodField('get_pictures')
class Meta:
model = Inspection # Options
fields = ('kilometers', 'inspection_date', 'pictures')
def get_pictures(self, obj):
return [each.public_url() for each in obj.pictures.all() ]