Reputation: 791
hi i'm trying to make a new foreignkey from different fields using to_field
but it return product
values instead no_invoice
class Model1(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
product = models.ForeignKey(Products,on_delete=models.CASCADE)
no_invoice = models.IntegerField(unique=True)
def __str__(self):
return self.product.name
class Model2(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
invoice = models.ForeignKey(Model1,to_field='no_invoice',on_delete=models.CASCADE)
is there something else i have to add ? thanks
Upvotes: 0
Views: 501
Reputation: 1394
Since no_invoice
is unique and seems like the serial number of Model1
, can you just make that the primary key? Like this:
class Model1(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
product = models.ForeignKey(Products,on_delete=models.CASCADE)
no_invoice = models.IntegerField(primary_key=True)
def __str__(self):
return self.product.name #self should be included
class Model2(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
invoice = models.ForeignKey(Model1,on_delete=models.CASCADE)
PS: You can also take a look at using a OneToOne
relationship instead of Foreign Key if the relationship from Model2 to Model1 is OneToOne
.
Upvotes: 1
Reputation: 380
ForeignKey.to_field The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True.
In your case There is nothing to add.
When you try to fetch the foreign key field, It return all related Model1 objects in a QuerySet
your str method is wrong . you have to fetch it with self. like below
def __str__(self):
return self.product.name
By default this method returns id(primary key) of the model object As your str method is returning product name when you try to print or render the foreign key field the string representation of the Model1 object is returned i.e. Product name.
Instead if you want to get your no_invoice field
you can replace your str with
def __str__(self):
return self.no_invoice
or
you have access to the whole object. you can also do it this way in your views.py.
m2_object = Model2.objects.all().first()
print(m2_object.invoice.no_invoice) #this will give your no_invoice value
ref: https://docs.djangoproject.com/en/3.0/ref/models/fields/
Upvotes: 1