Home > other >  dfr TypeError: unsupported operand type(s) for : 'Office' and 'str'
dfr TypeError: unsupported operand type(s) for : 'Office' and 'str'

Time:11-22

I'm trying to concatenate some fields ex. When I do this in postman

{
"sem": "2",
"sy": "2021-2022",
"remarks": "test",
"resolution": "test",
"studid": "2012-5037"
}

this is the customuser I made enter image description here The cl_itemid shoud be OSA-2021-2022-2

class ClearanceItemSerialize(serializers.ModelSerializer):
class Meta:
    model = ClearanceItem
    fields = '__all__'

def create(self, validated_data):
    validated_data["office"] = self.context["request"].user.officeid
    validated_data["recorded_by"] = self.context["request"].user.userid
    validated_data["cl_itemid"] = self.context["request"].user.officeid   '-'   validated_data.get('sy')   '-'   validated_data.get('sem')
    return super().create(validated_data)

above is the code

but it's throwing me an error TypeError: unsupported operand type(s) for : 'Office' and 'str'

if I use userid instead

validated_data["cl_itemid"] = self.context["request"].user.userid   '-'   validated_data.get('sy')   '-'   validated_data.get('sem') 

it's working

321-05   2021-2022-2 

What's happening here can somebody explain?

Edit: I added the models incase that's the problem

class ClearanceItem(models.Model):
cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id)
studid = models.CharField(max_length=9, blank=True, null=True)
office = models.ForeignKey('Office', models.DO_NOTHING, db_column='office', blank=True, null=True)
sem = models.CharField(max_length=1, blank=True, null=True)
sy = models.CharField(max_length=9, blank=True, null=True)
remarks = models.TextField(blank=True, null=True)

class Office(models.Model):
office_id = models.CharField(primary_key=True, max_length=50)
office_name = models.CharField(max_length=200)
office_head = models.CharField(max_length=8, blank=True, null=True)
designation = models.TextField(blank=True, null=True)
office_parent = models.CharField(max_length=50, blank=True, null=True)
deptlogo = models.TextField(blank=True, null=True)

class Meta:
    managed = False
    db_table = 'office'

Edit2: I try to remove all fks from customuser to office and clearance_item to office and its working idk why

Edit3: I try to add str in validated_data["cl_itemid"] = str(validated_data.get('office'))

When I check the value it's (Office object (OSA)1), is there a way can i get only the OSA part?

CodePudding user response:

The error says clearly that cannot concatenate a string with an Office instance. So you should try to use self.context["request"].user.officeid.office_id because most likely on your customer model you have something like this

class Customer(models.model)
...
   officeid = models.ForeignKey('Office', db_column='officeid' ...)

...

Therefore accessing user.officeid will get you the entire Office object.

  • Related