Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

How to create Django Model with combination of 2 models

I want to create one Django models which is the combination of 2 models like,

class Employee(models.Model):
  emp_id = models.CharField(max_length=45, primary_key=True, null=False)
  name = models.CharField(max_length=45)
  age = models.IntegerField()
  dob = models.DateField()
  addr = models.CharField(max_length=45)

class designtion(models.Model):
  emp_id = models.charField(max_length=45)
  role_name =  models.charField(max_length=45)
  starts_from = models.DateField()
  ends_on = models.DateField()

i want to create a combined models from these 2,

class EmpDetails(models.Model):
  name = models.CharField(max_length=45)
  role_name =  models.charField(max_length=45)

i am using django-rest-framework is their any best way to do like this?

Upvotes: 0

Views: 618

Answers (2)

PatDuJour
PatDuJour

Reputation: 975

If you are creating a many-to-many relationship for Employee and designtion(btw you should capitalize this), Django has support for M2M Field It basically create a JOIN table under the hood, but it give you all the methods you would need to perform lookup, creation, etc..

If you want future proof just in case you are moving away from Django and want all your models and methods reusable, then you can create your EmpDetails table manually like such:

class EmpDetails(models.Model):
    ... //other fields omitted, add as you need them
    employee = models.ForeignKey(Employee)
    designtion = models.ForeignKey(designtion)

Upvotes: 0

Samet Genc
Samet Genc

Reputation: 281

If you want, you can try this.

models.py

class designtion(models.Model):
    emp_id = models.charField(max_length=45)
    role_name =  models.charField(max_length=45)
    starts_from = models.DateField()
    ends_on = models.DateField()
    employee = models.ForeignKey(Employee, related_name="designition_employee")

serializers.py

from .models import designtion, EmpDetails
class DesigntionSerializer(serializers.ModelSerializer):
    hr_employee = serializers.ReadOnlyField(source='employee.name', read_only=True)
    class Meta:
        model = designtion
        exclude = ()

    def create(self, validated_data):
        name = validated_data.get('employee').name
        role_name = validated_data.get('role_name')
        EmpDetails.objects.create(name=name, role_name=role_name)
        return super(DesigntionSerializer, self).create(validated_data)

Do not forget migrate when added employee field to designtion model.

Upvotes: 1

Related Questions