1

我一直在努力解决这个问题。我正在使用 CSV 在 django 中导入数据,但这不是我的问题。

插入数据时出现此错误:

IntegrityError at /import-user-profile/
insert or update on table "association_userprofile_club" violates foreign key constraint "association_userprofile_club_club_id_fkey"
DETAIL:  Key (club_id)=(0) is not present in table "association_club".

使用 postgreSQL,不知道是不是这个原因。

以下是相关型号:

class UserProfile(models.Model):  
    user = models.OneToOneField(User)  
    membership_number = models.CharField(max_length=30,help_text='Membership number.')
    club = models.ManyToManyField(Club)
    date_joined = models.DateField(blank=True)
    street_address = models.CharField(max_length=100,help_text='Max 100 characters.',blank=True)
    suburb = models.CharField(max_length=40,help_text='Max 40 characters.',blank=True)
    postcode = models.CharField(max_length=10,help_text='Max 6 characters.',blank=True)
    state = models.CharField(max_length=30,help_text='Max 4 characters.',blank=True)
    home_phone = models.CharField(max_length=30,help_text='Max 30 characters.',blank=True)
    mobile_phone = models.CharField(max_length=30,help_text='Max 30 characters.',blank=True)
    ticketed_steward = models.CharField(max_length=1, choices=[('0', 'No'), ('1', 'Yes')],blank=True)
    ticketed_time_keeper = models.CharField(max_length=1, choices=[('0', 'No'), ('1', 'Yes')],blank=True)
    AFA_judge = models.CharField(max_length=1, choices=[('0', 'No'), ('1', 'Yes')],blank=True)
    associate_members = models.ManyToManyField(User,blank=True, related_name='+')

    def __str__(self):  
          return "%s's profile" % self.membership_number

class Club(models.Model):
    club_name = models.CharField(max_length=50,help_text='Name of the club, MAX 50 characters.')
    club_coordinater = models.CharField(max_length=50,blank=True)
    contact_email = models.EmailField(blank=True)
    contact_phone = models.CharField(max_length=30,blank=True)
    contact_fax = models.CharField(max_length=30,blank=True)
    address_location = models.CharField(max_length=50,blank=True)
    address_suburb = models.CharField(max_length=50,blank=True)
    address_postcode = models.CharField(max_length=50,blank=True)
    address_state = models.CharField(max_length=4,help_text='State the club is in, MAX 4 characters.',blank=True)
    incorporated = models.CharField(max_length=3, choices=[('0', 'No'), ('1', 'Yes')],blank=True)
    old_id = models.CharField(max_length=20,blank=True)
    website = models.URLField(blank=True)
    joined = models.DateField(blank=True)

    def __unicode__(self):
        return self.club_name

这应该可以正常工作,因为俱乐部正在正确返回。

def import_user_profile(request):
    if request.user.is_authenticated():
        file = database_loc + "tblHandlers.csv"
        data = ""
        with open(file, 'rb') as f:
            reader = csv.reader(f)
            for row in reader:
                if row[0] != "pkMemberNumber":
                    #0:pkMemberNumber 1:Club 2:fldContactOpen 3:fldLastName 4:fldFirstName 5:fldStreet 6:fldSuburb 7:fldState 8:fldPostcode 9:fldHome 10:fldMobile 11:fldEmail 12:fldJunior 13:fldNewsletter 14:fldNotes 15:dtejoined 16:dteExpiry 17:dateRenewed 18:fldFinMem1 19:fldFinMem2 20:fldDOB 21:fldHanderAge 22:fldStewTicket 23:fldTimeTicket 24:fldSnrTimeTicket
                    user = User.objects.get(username=row[0]+row[4]+row[3])

                    try:
                        club = Club.objects.get(club_name=str(row[1]))
                        club.save()
                    except:
                        club = Club.objects.get(club_name="No Club")
                        club.save()

                    try:
                        profile = UserProfile.objects.get(user=user)
                    except:
                        profile = UserProfile(user=user)

                    #profile.user=user
                    profile.membership_number=row[0]
                    thing = str(club.id)
                    profile.club=thing
                    profile.date_joined=date_re(row[15])
                    profile.street_address=row[5]
                    profile.suburb=row[6]
                    profile.postcode=row[8]
                    profile.state=row[7]
                    profile.home_phone=row[9][0:30]
                    profile.mobile_phone=row[10]
                    profile.ticketed_steward=row[22]
                    profile.ticketed_time_keeper=row[23]
                    profile.AFA_judge="0"
                    profile.save()

                    user_receipts = UserReceipts(user_id=profile.id,recept="",date_paid=date_re(row[17]),membership_valid_to=date_re(row[16]))  
        html = "<html><body>" + data + "</body></html>"
        return HttpResponse(html)

Django说问题发生在:

profile.club=thing 

一些帮助可以挽救我的理智!谢谢

4

1 回答 1

2
 try:
     club = Club.objects.get(club_name=str(row[1]))
     club.save() # <-- You don't need to save. You haven't changed anything on the club.
 except:
     club = Club.objects.get(club_name="No Club")
     club.save() # <-- You don't need to save. You haven't changed anything on the club.

django 声明的模型 id 是数字的,所以不要使用thing = str(club.id).

此外,使用属性pk比使用属性更可取,id因为pk它将始终指向真正的主键名称。这意味着如果您更改了模型的主键,则无需更改id代码中的所有访问权限。

您需要更改profile.club=thing为,profile.club.add(club.pk)因为您的club属性被声明为 a models.ManyToManyField(Club),它是一系列Club对象,而不是单个对象。

或者...您可以更改它并使用models.ForeignKey(Club)与属性名称 ( ) 更一致的a club(仅在您的用户只能同时是一个俱乐部的成员时这样做)

于 2013-02-12T02:12:57.630 回答