django-rest-auth
django-rest-auth copied to clipboard
Foreign Key to a user Custom Model
Hi.
I have a problem.
I want to make a relationship many to one to my model user with company.
I have created my business model, and my user model with a one-to-one relationship with the original User model.
model.py
from django.db import models
from django.contrib.auth.models import User
class Empresa(models.Model):
NombreEmpresa = models.CharField(max_length=120)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company_name = models.ForeignKey(Empresa)
serializers.py
class EmpresaSerializer(serializers.Serializer):
class Meta:
model = Empresa
field = ('id','nombreEmpresa')
class UserSerializer(UserDetailsSerializer):
company_name = serializers.CharField(source="userprofile.company_name")
# company_name = serializers.ModelSerializer(EmpresaSerializer(many=False, read_only=True))
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('company_name',)
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
company_name = profile_data.get('company_name')
instance = super(UserSerializer, self).update(instance, validated_data)
profile = instance.userprofile
if profile_data and company_name:
profile.save()
return instance
The point is that I do not understand how to show the foreign key of the company when I log in or when I consult the endpoint / rest-auth / user
If there is another way to assign multiple users to another model, I would appreciate it if you would guide me ..
Thank you
I await your comments.
Relacionship ManyToOne in django ?