我的项目中有以下模型
class TicketCounter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ticket_counter_name = models.CharField(max_length=100, default="")
class TicketCategory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ticket_category_name = models.CharField(max_length=100, default="")
ticket_category_rate = models.CharField(max_length=100, default="")
class WorkerToTicketCounter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ticket_counter = models.ForeignKey(TicketCounter, related_name="workers")
worker = models.ForeignKey(User, related_name='ticket_counter')
worker_to_ticket_counter_is_deleted = models.BooleanField(default=False)
class TicketCounterToCategory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ticket_counter = models.ForeignKey(TicketCounter, related_name="categories")
ticket_category = models.ForeignKey(TicketCategory)
每个TicketCounter
将有一个worker(用户)和TicketCategory
个。当工作人员登录到Android应用程序时。他将必须获取诸如email
first_name
和'last_name'之类的详细信息。我是用下面的序列化器完成的。
class MeSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'pk',
'first_name',
'last_name',
'email',
)
在我的应用程序中,不仅需要详细信息,而且需要与他关联的TicketCounter
。所以我像下面一样添加了ticket_counter
class MeSerializer(serializers.ModelSerializer):
ticket_counter = serializers.SerializerMethodField(read_only=True)
class Meta:
model = User
fields = (
'pk',
'first_name',
'last_name',
'email',
'ticket_counter',
)
def get_ticket_counter(self, user):
qs = user.ticket_counter.filter(worker_to_ticket_counter_is_deleted=False)
if qs.exists() and hasattr(qs.first().ticket_counter, 'ticket_counter_name'):
return qs.first().ticket_counter.ticket_counter_name
return "--"
但是现在我需要在ticket_counter
中的对象列表中获取该MeSerializer
的关联类别。可能吗?