我有兩個模型Requests
和Events
有外鍵回到User
模型。當試圖使用Django Rest Framework發佈外鍵數據時,我收到一個空約束錯誤。看來django不接受user_id(requester_id
和event_admin_id
)引用。在可瀏覽的API中,外鍵部分(requester_id
和event_id
)不存在。它被某物隱藏了嗎?請注意,event_participant僅由外鍵組成,但它們在發佈時顯示在可瀏覽的API中。我不知道這可能是區別models.ForeignKey字段沒有顯示在可瀏覽的API
Missing event_admin_id foreignkey field Missing request_admin_id fk field
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
user_job_description = models.CharField(max_length = 200)
user_profile_pic = models.ImageField(null = True, blank = True)
class Event(models.Model):
def __str__(self):
return self.event_name
event_name = models.CharField(max_length = 100)
event_location = models.CharField(max_length = 100)
event_description = models.TextField(max_length = 300)
admin_user_id = models.ForeignKey(User, related_name = 'event_admin')
class Request(models.Model):
def __str__(self):
return self.request_desc
requester_user_id = models.ForeignKey(User, related_name = 'requests')
request_desc = models.TextField(max_length = 100)
fulfiller_user_id = models.IntegerField(null = True, blank = True)
fulfilled_status = models.BooleanField()
class Event_Participant(models.Model):
def __str__(self):
return str(self.event_id)
user_id = models.ForeignKey(User, related_name = 'event_attendee')
event_id = models.ForeignKey(Event, related_name = 'event')
serializers.py
from django.contrib.auth import get_user_model
from crewboardsdb.models import Event
from crewboardsdb.models import Request
from crewboardsdb.models import Event_Participant
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
requests = serializers.StringRelatedField(many = True)
event_admin = serializers.StringRelatedField(many = True)
event_attendee= serializers.StringRelatedField(many = True)
class Meta:
model = get_user_model()
fields = ('id','username','first_name','last_name','email','user_job_description','event_admin','requests', 'event_attendee',)
class EventSerializer(serializers.ModelSerializer):
admin_user_id = serializers.StringRelatedField()
class Meta:
model = Event
fields = ('id', 'event_name', 'admin_user_id', 'event_description', 'event_location',)
lookup_field = 'admin_user_id'
class RequestSerializer(serializers.ModelSerializer):
requester_user_id = serializers.StringRelatedField()
class Meta:
model = Request
fields = ('id', 'request_desc', 'fulfilled_status','requester_user_id','fulfiller_user_id',)
lookup_field = 'requester_user_id'
class EventParticipantSerializer(serializers.ModelSerializer):
class Meta:
model = Event_Participant
fields = ('id', 'event_id', 'user_id')
我應該補充說,這些字段昨天可見,我不知道什麼可以改變。 – user2904913