按用户外键搜索类

时间:2017-09-19 20:40:25

标签: python mysql django

我搜索过高低,甚至介于两者之间,由于某种原因无法得出明确答案......

我正在使用django1.9并创建了这个模型:

class paymentInfo(models.Model):
    """
    Model for storing payment info
    - Username as ForeignKey from userToCard
    - Store payment token
    - Store last 4
    - Store card/bank name
    - Store bool value for Default method
    """

    username = models.ForeignKey(User, db_column='username', on_delete=models.CASCADE)
    token = models.CharField(max_length=10)
    last_4 = models.IntegerField()
    bank_name = models.CharField(max_length=50)
    default = models.BooleanField(default=0)

    class Meta:  # meta class to define the table name
        db_table = 'payment_methods'
        verbose_name_plural = 'Payment Methods'  # for the admin site display
        ordering = ('username',)

    def __str__(self):
        # in __str__  you should return a value of type string
        # so self.username changed to self.username.username          
        return self.username.username  # value displayed in admin view

我使用一些不同的用户名创建了一些对象,并希望按用户过滤掉paymentInfo对象。

当我存储对象时,数据库将user pk存储在username列下,而不是实际的用户名字符串。我不知道为什么,但这不是我的问题。

我的问题是,当我尝试使用paymentInfo.objectsusername过滤user pk时。我似乎无法过滤掉它,因此我通常得到的错误是:FieldError: Cannot resolve keyword 'username' into field. Choices are: bank_name, default, id, last_4, token

P.S。我正在使用MySQL

2 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您正试图通过用户名从表User过滤数据什么是外键。在这种情况下,这应该有帮助

paymentInfo.objects.filter(username__name='John')

答案 1 :(得分:0)

感谢提供的答案,我能够找到解决方案(主要使用@Aamir Adnan的方法。)

class paymentInfo(models.Model):
"""
Model for storing payment info
- Username as ForeignKey from userToCard
- Store payment token
- Store last 4
- Store card/bank name
- Store bool value for Default method
"""

user = models.ForeignKey(User, on_delete=models.CASCADE)
token = models.CharField(max_length=10)
last_4 = models.IntegerField()
bank_name = models.CharField(max_length=50)
default = models.BooleanField(default=0)

class Meta:  # meta class to define the table name
    db_table = 'payment_methods'
    verbose_name_plural = 'Payment Methods'  # for the admin site display
    ordering = ('user',)

def __str__(self):
    return self.user  # value displayed in admin view

def __unicode__(self):
    return '%s' % (self.user)

我班级内的新__unicode__是因为我没有收到此错误:

TypeError: coercing to Unicode: need string or buffer, User found