How can I get a ForeignKey field instead of a related object in Django?

I have it:

Class A(models.Model):
     name = models.CharField(max_length=50)

Class B(models.Model):
     a = models.ForeignKey(A)

class C(models.Model):
     a = models.ManyToManyField(A)

When I need an attribute ain an object C:

related_manager = getattr(object_c,'a') 

and this gives me ManyRelatedManager, but the problem is that I need an attribute ain the object B:

object_b2 = getattr(object_b,'a')

this gives me an object of class B and I need to know if ForeignKey or ManyToManyField, I mean, I need to getattr (something, "some_attribute") and get the models. * Not an object in itself.

+3
source share
2 answers

I came across this before with getattr. Auto-representation of a model is a solution.

, - _meta (ooooh, scary!).

object_b2._meta.get_field_by_name('a')[0]

[0] , . , , .

, , - _meta.fields , field.rel.to - , .

!

+6

A ForeignKey . , ManyToMany , ForeignKey unique .

-1

Source: https://habr.com/ru/post/1732425/


All Articles