35
loading...
This website collects cookies to deliver better user experience
php artisan
and generate the components that you need – at maximum, you have to do some configuration to make it fit eloquently into the rest of your app. I use Laravel's documentation as a gold standard in framework + technical documentation and wish more would follow suit.php artisan tinker
is easier to use and integrated more closely with the framework. It's an incredibly tiny detail, but tinker utilizes autoloading and allows you to reference models by namespaces, without having to import them. This is different from the Django manage.py shell
, where you have to import all of the modules and classes that you want to interact with.<?php
// App\Models\Employee.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
//
}
<?php
// App\Http\Controllers\API\EmployeeController.php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\Employee;
class EmployeeController extends Controller
{
public function show($id)
{
return response()->json(Employee::findOrFail($id));
}
}
# app/models/employee.py
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=255)
age = models.PositiveSmallIntegerField(null=True)
User
model, instead of just a user_id
), and create method fields that will return some value every time your object is being returned. Essentially, splitting a Laravel model returns a Django model + serializer. A serializer is technically an offering of DRF, but if you're building an API, you'll have this.
# app/serializers/employee.py
from rest_framework import serializers
from app.models import Employee
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ['name', 'age']
# app/views/employee.py
from rest_framework import generics
from app.models import Employee
from app.serializers import EmployeeSerializer
class EmployeeList(generics.ListCreateAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer