我正在设计一个系统,允许用户在预先配置的有序对象集中选择多个对象(比如5)(计数> 5)。基本上,用户必须选择一组9中的前5个对象。我必须保存这些条目并找出具有最大投票(最大选择)的对象和基于最右边条目的获胜者。
我的模特:
class User(AbstractUser):
'''Info about user '''
class Contest(models.Model):
name = models.CharField(max_length=255)
created = models.DateField(auto_now_add=True)
class ObjectsForContest(models.Model):
name = models.CharField(max_length=255)
contest = models.ManyToManyField('Contest', through='OrderedObjectsForContest')
class OrderedObjectsForContest(models.Model):
choice = models.ForeignKey(ObjectsForContest)
contest = models.ForeignKey(Contest, related_name='ordered_options')
order = models.PositiveIntegerField()
class Meta:
ordering = ['order']
class UserEntriesForContest(models.Model):
user = models.ForeignKey(User, related_name="entries_for_contest")
contest = models.ForeignKey(Contest, related_name='participating_users')
objects_selected = models.ManyToManyField(ObjectsForContest, through='OrderedChoicesByUser', null=True, blank=True)
def __unicode__(self):
return self.user.unique_id
class OrderedChoicesByUser(models.Model):
choice = models.ForeignKey(ObjectsForContest)
contest = models.ForeignKey(UserEntriesForContest)
order = models.PositiveIntegerField()
class Meta:
ordering = ['order']
我的序列化器非常简单。 串行器:
class ContestObjectsSerializer(serializers.ModelSerializer):
class Meta:
model = ObjectsForContest
exclude = ("contests", )
class ContestObjectsThroughSerializer(serializers.ModelSerializer):
choice = ContestObjectsSerializer()
class Meta:
model = OrderedObjectsForContest
exclude = ("id", )
class Contest(serializers.ModelSerializer):
winner = SimpleUserProfileSerializer() #this serializes the user and not included here.
choices = ContestObjectsThroughSerializer(many=True)
class Meta:
model = Contest
class UserEntriesForContestSerializer(serializers.ModelSerializer):
choices_made = ContestObjectsSerializer(many=True)
class Meta:
model = UserEntriesForContest
如何找到最大用户根据订单选择的选项?
实施例。 根据比赛的对象:(名称,顺序)
(Apple, 1), (Orange, 2), (Grapes, 3), (Mango, 4), (Apricot, 5), (Cherry, 6), (Guava, 7), (Jackfruit, 8), (Lime, 9)
我们假设有5个用户选择:
#User 1:
(Apple, 1), (Lime, 2), (Grapes, 3), (Mango, 4), (Apricot, 5)
#User 2:
(Apple, 1), (Orange, 2), (Lime, 3), (Mango, 4), (Apricot, 5)
#User 3:
(Apple, 1), (Orange, 2), (Grapes, 3), (Cherry, 4), (Apricot, 5)
#User 4:
(Apple, 1), (Orange, 2), (Lime, 3), (Cherry, 4), (Apricot, 5)
#User 5:
(Apple, 1), (Lime, 2), (Grapes, 3), (Cherry, 4), (Apricot, 5)
获奖名单应为:
(Apple, 1), (Orange, 2), (Grapes, 3), (Cherry, 3), (Apricot, 5)
我需要知道如何根据我的模型获得此列表。
答案 0 :(得分:0)
可以通过DRF中的SerializerMethodField完成多对多订单
students_listss = serializers.SerializerMethodField('get_students_list')
def get_students_list(self, instance):
return Student.objects\
.filter()\
.order_by('name')\
.values_list('name', flat=True)
您可以像往常一样在order_by()
中应用订单条件答案 1 :(得分:-1)
使用tastypie REST框架来获取详细信息。通过使用tatsypie,您可以使用http://django-tastypie.readthedocs.org/en/latest/fields.html#tomanyfield
访问文件