开发者

Django form post saving multiple records that violate the unique integrity check

开发者 https://www.devze.com 2023-03-17 09:00 出处:网络
I\'ve got a model for purposes of storing the scoring of a football game by quarter: class BoxScoreByQuarter( models.Model ):

I've got a model for purposes of storing the scoring of a football game by quarter:

class BoxScoreByQuarter( models.Model ):
    game_participant = models.ForeignKey( GameParticipant, verbose_name='game participant' )
    first_quarter = models.PositiveSmallIntegerField( blank=True, null=True, verbose_name='first quarter' )
    second_quarter = models.PositiveSmallIntegerField( blank=True, null=True, verbose_name='second quarter' )
    third_quarter = models.PositiveSmallIntegerField( blank=True, null=True, verbose_name='third quarter' )
    fourth_quarter = models.PositiveSmallIntegerField( blank=True, null=True, 开发者_如何学运维verbose_name='fourth quarter' )
    overtime = models.PositiveSmallIntegerField( blank=True, null=True, verbose_name='overtime' )
    final_score = models.PositiveSmallIntegerField( blank=True, null=True, verbose_name='final score' )

game_participant is a FK to the GameParticipant model and there should never be more than one BoxScoreByQuarter per participant in a game.

My view checks for the existence of a BoxScoreByQuarter and either updates it or creates a new one.

        try:
            initial_box = BoxScoreByQuarter.objects.get( game_participant=participant )
            box_score = BoxScoreByQuarterForm( submitted_data, instance=initial_box )
        except ObjectDoesNotExist:
            box_score = BoxScoreByQuarterForm( submitted_data )
            initial_box = None

        if box_score.is_valid():
            game_results = box_score.save()

For some reason, the save occasionally results in two or even more BoxScoreByQuarter records for a given participant. It doesn't happen all the time and there doesn't appear to be any pattern to it.

Is there a more reliable way of handling the form save that would guarantee the integrity of the data?


If you only want one BoxScoreByQuarter per GameParticipant then you should be using a OneToOneField instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消